﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using KL.Store.Web.Models;
using KL.Store.Data;
using KL.Store.Core;
using KL.Store.Core.Domain;
using KL.Store.Core.POS;
using KL.Store.Core.Domain.Enum;
using System.Data.SqlClient;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System.Collections.Specialized;
using KL.Store.Core.Ucuzu;
using System.Xml;
using PayU.AutomaticLiveUpdate;
using CaptchaMvc.HtmlHelpers;

namespace KL.Store.Web.Controllers
{
    //[Authorize]
    [RequireHttps]
    public class CartController : KL.Store.Core.Web.BaseController
    {
        #region Index

        public ActionResult Index()
        {
            
            eStoreUser.RedirectUrl = "/Cart/Index";
            return View();
        }

        #endregion

        #region Order

        public ActionResult Order()
        {
            return View();
        }

        #endregion

        #region Contract

        public ActionResult Contract(short CargoAddressId, short InvoiceAddressId, string PaymentType, decimal CargoPrice, decimal TotalPayment, int SelectedPos)
        {
            CartModel cartModel = new CartModel();

            if (eStoreUser.AccountId > 0)
            {
                cartModel.Contract = CreateContractText(CargoAddressId, InvoiceAddressId, PaymentType, CargoPrice, TotalPayment, SelectedPos);
            }

            return PartialView("Contract", cartModel);
        }

        #endregion

        #region CreateContractText

        private string CreateContractText(short CargoAddressId, short InvoiceAddressId, string PaymentType, decimal CargoPrice, decimal TotalPayment, int SelectedPos)
        {
            string posDescription = "";
            if (PaymentType == "110" || PaymentType == "KrediKart")
                PaymentType = "Kredi Kartı";
            else if (PaymentType == "120" || PaymentType == "HavaleEft")
                PaymentType = "Havale/Eft";
            else if (PaymentType == "130" || PaymentType == "PayPal")
                PaymentType = "PayPal";
            else if (PaymentType == "140" || PaymentType == "Mobil")
                PaymentType = "Mobil";
            else if (PaymentType == "150" || PaymentType == "PayU")
                PaymentType = "PayU";
            else if (PaymentType == "160" || PaymentType == "KapidaOdeme")
                PaymentType = "Kapıda Ödeme";

            if (PaymentType == "Kredi Kartı" && SelectedPos > 0)
            {
                PosDDL posDDL = Parameters.PosListDDL.Where(p => p.PosId == SelectedPos).FirstOrDefault();
                if (posDDL != null)
                {
                    posDescription = posDDL.ContractNote;
                }
            }

            string contract = "";
            if (eStoreUser.AccountId > 0)
            {
                contract = dbPage.Get(2);
                Address InvoiceAddress = dbAddress.Get(eStoreUser.AccountId, InvoiceAddressId);
                Address DeliveryAddress = dbAddress.Get(eStoreUser.AccountId, CargoAddressId);
                if (InvoiceAddress == null) { InvoiceAddress = new Address(); }
                if (DeliveryAddress == null) { DeliveryAddress = new Address(); }

                contract = contract.Replace("{Firstname}", string.IsNullOrEmpty(InvoiceAddress.Name) ? eStoreUser.FirstName + " " + eStoreUser.LastName : InvoiceAddress.Name);
                contract = contract.Replace("{Date}", Parameters.Now.ToShortDateString()).Replace("{MobilePhone}", eStoreUser.Mobile).Replace("{Phone}", InvoiceAddress.Phone);
                contract = contract.Replace("{TaxOffice}", InvoiceAddress.TaxOffice).Replace("{TaxNo}", InvoiceAddress.TaxNo).Replace("{Email}", eStoreUser.Email);
                contract = contract.Replace("{InvoiceAdress}", InvoiceAddress.Address1 + " " + InvoiceAddress.Address2 + " " + InvoiceAddress.County + " " + InvoiceAddress.CityName);
                contract = contract.Replace("{DeliveryAdress}", DeliveryAddress.Address1 + " <br />" + DeliveryAddress.Address2 + "  " + DeliveryAddress.CityName + "  " + DeliveryAddress.PostalCode);
                contract = contract.Replace("{DeliveryName}", string.IsNullOrEmpty(DeliveryAddress.Name) ? eStoreUser.FirstName + " " + eStoreUser.LastName : DeliveryAddress.Name);
                contract = contract.Replace("{CargoPrice}", CargoPrice.ToString("###,##0.00 TL")).Replace("{TotalPayment}", TotalPayment.ToString("###,###,##0.00 TL"));
                contract = contract.Replace("{PosDescription}", posDescription);

                IList<Cart> Basket = dbCart.GetList(eStoreUser.AccountId, eStoreUser.AccountType);
                string table = "<table style='border: 1px dashed'><tr><td><b>Ürün</b></td><td><b>Adet</b></td><td><b>Birim</b></td></tr>";

                foreach (var rows in Basket)
                {
                    table += "<tr>";
                    table += "<td>" + rows.ProductName + "</td> <td> " + rows.Qty.ToString("###,###.###") + "</td><td>" + rows.Birim + "</td>";
                    table += "</tr>";
                }
                table += "</table>";

                contract = contract.Replace("{ProductTable}", table).Replace("{PaymentType}", PaymentType);
            }
            return contract;
        }

        #endregion

        #region DeliveryContract

        public ActionResult DeliveryContract()
        {
            CartModel cartModel = new CartModel();

            if (eStoreUser.AccountId > 0)
            {
                cartModel.Contract = Parameters.DeliveryContract;
            }

            return PartialView("DeliveryContract", cartModel);
        }

        #endregion

        #region CustomCheckOutAgreement

        public ActionResult CustomCheckOutAgreement()
        {
            CartModel cartModel = new CartModel();
            cartModel.Contract = Parameters.CustomCheckOutAgreement;
            return PartialView("CustomCheckOutAgreement", cartModel);
        }

        #endregion

        #region Get

        [Child]
        public ActionResult Get()
        {
            CartModel cartModel = new CartModel();

            if (eStoreUser.AccountId > 0)
            {
                cartModel.Products = dbCart.GetList(eStoreUser.AccountId, eStoreUser.AccountType);
            }
            if (cartModel.Products == null) cartModel.Products = new List<Cart>();

            RefreshCartSummary();
            cartModel.TotalPrice = eStoreUser.TotalPrice + eStoreUser.InstallmentPrice + eStoreUser.InstallmentTax;
            cartModel.Tax = eStoreUser.Tax + eStoreUser.InstallmentTax;
            cartModel.Price = cartModel.TotalPrice - cartModel.Tax;
            cartModel.TotalPriceCreditCard = Math.Round(eStoreUser.TotalPrice / Parameters.CreditCardDiscount, 2);
            cartModel.AccountType = eStoreUser.AccountType;
            cartModel.BasketLocked = eStoreUser.BasketLocked;

            return PartialView("Get", cartModel);
        }

        #endregion

        #region GetMinimal

        [Child]
        public ActionResult GetMinimal(bool showPhotos = false, bool ShowAcrIcrLinks = false)
        {
            CartModel cartModel = new CartModel();

            if (eStoreUser.AccountId > 0)
            {
                cartModel.Products = dbCart.GetList(eStoreUser.AccountId, eStoreUser.AccountType);
            }
            if (cartModel.Products == null) cartModel.Products = new List<Cart>();

            RefreshCartSummary();
            cartModel.TotalPrice = eStoreUser.TotalPrice + eStoreUser.InstallmentPrice + eStoreUser.InstallmentTax;
            cartModel.Tax = eStoreUser.Tax + eStoreUser.InstallmentTax;
            cartModel.Price = cartModel.TotalPrice - cartModel.Tax;
            cartModel.TotalPriceCreditCard = Math.Round(eStoreUser.TotalPrice / Parameters.CreditCardDiscount, 2);
            cartModel.ShowPhotos = showPhotos;
            cartModel.ShowAcrIcrLinks = ShowAcrIcrLinks;
            cartModel.BasketLocked = eStoreUser.BasketLocked;

            return PartialView("GetMinimal", cartModel);
        }

        #endregion


        #region CheckOut

        public ActionResult CheckOut()
        {
            if (!Parameters.AllowVisitorsToUsingCart && eStoreUser.AccountType == 1)
            {
                eStoreUser.RedirectUrl = "/Cart/CheckOut";
                string url = "/Account/Login";
                return Redirect(url);
            }

            eStoreUser.RedirectUrl = "/Cart/CheckOut";

            return View();
        }
        #endregion

        #region GetCheckOut

        [Child]
        //[Authorize]
        public ActionResult GetCheckOut()
        {
            if (!Parameters.AllowVisitorsToUsingCart && eStoreUser.AccountType == 1)
            {
                string url = "/Account/Login?ReturnUrl=/Cart/Checkout";
                return Redirect(url);
            }
            ViewData.ModelState.Clear();
            var ccoModel = Get_ccoModel();

            ccoModel.ContractTotalPrice = ccoModel.TotalPayment;
            ccoModel.UserId = eStoreUser.AccountId;
            ccoModel.UserType = eStoreUser.AccountType;
            ccoModel.ItemCount = eStoreUser.ItemCount;
            ccoModel.AddressCompleted = 0;
            ccoModel.VoucherAvailable = 0;
            ccoModel.Kimlik = dbAccount.GetUserIdentity(eStoreUser.AccountId);

            if (ccoModel.SelectedPos == 0)
            {
                ccoModel.SelectedPos = ccoModel.PosList.FirstOrDefault().PosId;
                ccoModel.PosInstallmentList = dbPos.GetInstallmentListPayment(ccoModel.SelectedPos, ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard - ccoModel.CargoTotalPrice : ccoModel.SummaryCargo.CartTotalPrice, ccoModel.SummaryCargo.CartTotalPrice, ccoModel.CampaignTotalPaymentWithCreditCard > 0 ? ccoModel.CampaignTotalPaymentWithCreditCard : ccoModel.CampaignTotalPayment, ccoModel.CampaignTotalPayment, ccoModel.CargoPrice, ccoModel.CargoPrice2);

                ccoModel.SelectedInstallment = ccoModel.PosInstallmentList.FirstOrDefault().InstallmentNumber;
                ccoModel.SelectedPosDescription = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Description;
                ccoModel.SelectedPosEnabled3D = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Enabled3D;
                ccoModel.Type3D = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Type3D;
            }



            if (Session["Error_3D"] != null)
            {
                ccoModel.Message4 = Session["Error_3D"].ToString();
                Session["Error_3D"] = null;
            }

            return PartialView("GetCheckout", ccoModel);
        }

        #endregion

        #region Get_ccoModel

        private CartCheckOutModel Get_ccoModel()
        {
            RefreshCartSummary();

            CartCheckOutModel ccoModel = new CartCheckOutModel();

            CartModel cartModel = new CartModel();
            cartModel.Products = dbCart.GetList(eStoreUser.AccountId, eStoreUser.AccountType);
            ccoModel.BasketLocked = eStoreUser.BasketLocked;

            #region First & Last Name & Item Count

            ccoModel.UserName = eStoreUser.FirstName + " " + eStoreUser.LastName;
            ccoModel.UserId = eStoreUser.AccountId;
            ccoModel.ItemCount = eStoreUser.ItemCount;
            ccoModel.UserType = eStoreUser.AccountType;

            #endregion

            #region Ürün stok kontrolü

            decimal toplamDesi = 0;
            bool freeAvailable = false;
            foreach (Cart cart in cartModel.Products)
            {
                Product product = dbProduct.Get(cart.ProductId, eStoreUser.AccountId);
                var productStock = product.InStockDepo;
                var productInCart = (int)cart.Qty;
                var productInCartExtra = productInCart - productStock;
                var productToCartAvailable = productStock - productInCart;
                toplamDesi += product.Desi;
                if (productStock < 1 && product.CheckStock && !Parameters.AllowEndedProducts)
                {
                    ccoModel.Message9 = "<span class=\"checkOut-Error-Text\">\"" + product.ProductName + "\" ürününden stoklarımızda hiç kalmadı. Sepetinize giderek bu ürünü sepetten çıkartmanız gerekmektedir.</span>";
                }
                else if (productInCart > productStock && product.CheckStock && !Parameters.AllowEndedProducts)
                {
                    ccoModel.Message9 = "<span class=\"checkOut-Error-Text\">\"" + product.ProductName + "\" ürününden stoklarımızda " + (Convert.ToInt32(productStock)).ToString() + " adet kaldı. Sepetinize giderek bu üründen " + (Convert.ToInt32(productInCartExtra)).ToString() + " adet eksiltmeniz gerekmektedir.</span>";
                }
                if (product.FreeCargo)
                {
                    freeAvailable = true;
                }
            }

            #region taksit sayısı

            ccoModel.MaxInstallmentCount = 9999;
            foreach (Cart cart in cartModel.Products)
            {
                if (cart.MaxInstallmentCount <= ccoModel.MaxInstallmentCount && cart.MaxInstallmentCount > 0)
                {
                    ccoModel.MaxInstallmentCount = cart.MaxInstallmentCount;
                }
            }

            #endregion

            //Mesaj
            //dataOK = false;
            //ccoModel.Message9 = "<font color=red>Teslimat ve fatura adres bilgilerini kontrol ediniz.</font>";
            #endregion

            #region Cargo Addresses DDL

            ccoModel.CargoAddresses = dbAddress.GetDDL(eStoreUser.AccountId, eStoreUser.AccountType);

            #region First Address Assigned to Cargo and Invoice AdressIds Only if cart has own items not only WishList items

            if (ccoModel.CargoAddresses.Count > 0) // && ccoModel.SummaryCargo.CartItemCount > 0)
            {
                ccoModel.CargoAddressId = ccoModel.CargoAddresses.FirstOrDefault().AddressId;
                ccoModel.InvoiceAddressId = ccoModel.CargoAddresses.FirstOrDefault().AddressId;

                ccoModel.CargoAddress = dbAddress.Get(eStoreUser.AccountId, ccoModel.CargoAddressId);
                ccoModel.InvoiceAddress = dbAddress.Get(eStoreUser.AccountId, ccoModel.InvoiceAddressId);
            }
            else
            {
                ccoModel.CargoAddresses.Insert(0, new AddressDDL { AddressId = 0, AddressName = "Adres Giriniz" });
            }

            #endregion

            if (ccoModel.CargoAddresses == null)
            {
                ccoModel.CargoAddresses = new List<AddressDDL>();
            }


            #endregion

            #region Guarantors DDL
            ccoModel.GuarantorList = eStoreUser.AccountType == 0 ? dbAccount.GetGuarantorDDL(eStoreUser.AccountId) : dbAccount.GetVisitorGuarantorDDL(eStoreUser.AccountId);

            if (ccoModel.GuarantorList.Count > 0)
            {
                ccoModel.Guarantor1Id = ccoModel.GuarantorList.FirstOrDefault().AccountId;
                ccoModel.Guarantor1 = eStoreUser.AccountType == 0 ? dbAccount.GetGuarantor(ccoModel.Guarantor1Id) : dbAccount.GetVisitorGuarantor(ccoModel.Guarantor1Id);
                if (ccoModel.GuarantorList.Count() > 1)
                {
                    ccoModel.Guarantor2Id = ccoModel.GuarantorList.Skip(1).FirstOrDefault().AccountId;
                    ccoModel.Guarantor2 = eStoreUser.AccountType == 0 ? dbAccount.GetGuarantor(ccoModel.Guarantor2Id) : dbAccount.GetVisitorGuarantor(ccoModel.Guarantor2Id);
                }
                ccoModel.GuarantorList.Insert(0, new GuarantorDDL { AccountId = 0, FullName = "Kefil Seçiniz" });
                ccoModel.GuarantorList = ccoModel.GuarantorList.OrderBy(o => o.AccountId).ToList();
            }
            else
            {
                ccoModel.GuarantorList.Insert(0, new GuarantorDDL { AccountId = 0, FullName = "Kefil Ekleyiniz" });
            }

            if (ccoModel.GuarantorList == null)
            {
                ccoModel.GuarantorList = new List<GuarantorDDL>();
            }
            #endregion

            #region Cart Summary

            //ccoModel.Summary.TotalPrice = eStoreUser.TotalPrice;
            //ccoModel.Summary.TotalQty = eStoreUser.TotalQty;
            //ccoModel.Summary.ItemCount = eStoreUser.ItemCount;

            #endregion

            ccoModel.VoucherList = dbVoucher.GetList(eStoreUser.AccountId);
            ccoModel.CargoList = Parameters.CargoList;
            if (ccoModel.VoucherList == null) ccoModel.VoucherList = new List<Voucher>();
            var voucherSUM = ccoModel.VoucherList.Where(v => v.Selected == true).Sum(i => i.Payment);

            #region Cargo Summary

            ccoModel.SummaryCargo = dbCart.GetSummaryCargo(eStoreUser.AccountId, eStoreUser.AccountType, ccoModel.SelectedCargoCompanyId, ccoModel.CargoAddress.City, Parameters.CreditCardDiscount, Parameters.TransferDiscount, Parameters.CargoCalculateForSameProduct);
            ccoModel.CargoPrice = 0;
            ccoModel.CargoPrice2 = 0;

            #region Kargo ücreti getir
            if (ccoModel.SummaryCargo != null)
            {
                if (ccoModel.SummaryCargo.CartItemCount > 0)
                {
                    ccoModel.CargoPrice = Math.Round(ccoModel.SummaryCargo.CartCargoPrice * (Parameters.SetCargoPricesWithoutTax ? 1 : Parameters.CargoList.Where(c => c.CargoId == ccoModel.SelectedCargoCompanyId).FirstOrDefault().Tax), 2);
                }

                if (ccoModel.SummaryCargo.ListItemCount > 0)
                {
                    ccoModel.CargoPrice2 = Math.Round(ccoModel.SummaryCargo.ListCargoPrice * (Parameters.SetCargoPricesWithoutTax ? 1 : Parameters.ListCargoProductTax), 2);
                }
            }
            #endregion

            #region Tek Kargo (Sabit Kargo)

            if (Parameters.OnlyOneCargoPrice > 0 && !freeAvailable)
            {
                ccoModel.CargoPrice = Parameters.OnlyOneCargoPrice;
            }

            #endregion

            #region Cargo Min Limit Control "X TL Üzeri Y TL (2031-2032)"

            if (Parameters.CargoMinLimit > 0 && ccoModel.SummaryCargo.CartTotalPriceCreditCard > Parameters.CargoMinLimit && ccoModel.CargoPrice > Parameters.CargoMinLimitPrice)
            {
                ccoModel.CargoPrice = Parameters.CargoMinLimitPrice;
            }

            #endregion

            #region Cargo Free Limit Control (Ref2015)

            if (Parameters.CargoLimit > 0 && ccoModel.SummaryCargo.CartTotalPriceCreditCard > Parameters.CargoLimit)
            {
                ccoModel.CargoPrice = 0;
                ccoModel.CargoPrice2 = 0;
            }

            #endregion

            #region Ücretsiz Kargo Varsa Tümünü Ücretsiz Yap

            if (ccoModel.CargoPrice > 0 && toplamDesi <= Parameters.FreeCargoDesiLimit)
            {
                var freeCargoProductAvailable = false;
                foreach (Cart cart in cartModel.Products)
                {
                    Product product = dbProduct.Get(cart.ProductId, eStoreUser.AccountId);
                    if (product.FreeCargo)
                    {
                        freeCargoProductAvailable = true;
                        break;
                    }
                }
                if (freeCargoProductAvailable)
                {
                    ccoModel.CargoPrice = 0;
                }
            }

            #endregion

            #region Şehiriçi ücretsiz kargo kontrolü

            IList<CityDDL> Cities = dbCity.GetFreeCargoCities();
            var freeCargoInCityProductAvailable = false;
            foreach (Cart cart in cartModel.Products)
            {
                Product product = dbProduct.Get(cart.ProductId, eStoreUser.AccountId);
                if (product.FreeCargoInCity)
                {
                    freeCargoInCityProductAvailable = true;
                    break;
                }
            }
            if (freeCargoInCityProductAvailable && Cities.Any(x => x.CityName == ccoModel.CargoAddress.CityName))
            {
                ccoModel.FreeCargoInCityAvailable = true;
                ccoModel.SelectedCargoCompanyId = ccoModel.CargoList.Where(c => c.OnlyFreeCargoInCity).FirstOrDefault().CargoId;
            }
            else
            {
                ccoModel.FreeCargoInCityAvailable = false;
                ccoModel.SelectedCargoCompanyId = ccoModel.CargoList.Where(c => c.OnlyFreeCargoInCity == false).FirstOrDefault().CargoId;
            }

            #endregion

            #region farklı fatura adresi
            if (ccoModel.CargoAddressId != ccoModel.InvoiceAddressId && ccoModel.CargoWithInvoice == false)
            {
                ccoModel.CargoInvoicePrice = dbCargoRange.GetRangePrice(eStoreUser.AccountId, ccoModel.SelectedCargoCompanyId, 0).Price;
                ccoModel.CargoPrice = ccoModel.CargoPrice + Math.Round(ccoModel.CargoInvoicePrice * Parameters.CargoList.Where(c => c.CargoId == ccoModel.SelectedCargoCompanyId).FirstOrDefault().Tax, 2);
            }
            #endregion

            #region kapıda ödeme
            if (ccoModel.PaymentType == PaymentTypes.KapidaOdeme)
            {
                ccoModel.CargoPrice = ccoModel.CargoPrice + Parameters.AdditionFeeForPaymentAtDoor;  // Kapıda Ödeme Ek İşlem Ücreti
            }
            #endregion

            #region Nakliye ve Montaj

            if (Parameters.CityList.Where(o => o.CityId == ccoModel.CargoAddress.City).Count() > 0)
            {
                var regionId = Parameters.CityList.Where(c => c.CityId == ccoModel.CargoAddress.City).FirstOrDefault().RegionId;
                if (regionId > 0)
                {
                    var region = Parameters.RegionList.Where(r => r.Id == regionId).FirstOrDefault();
                    foreach (var pr in cartModel.Products)
                    {
                        if (pr.TransportNeeded)
                        {
                            ccoModel.TransportAvailable = true;
                        }
                        if (pr.InstallationSelected && region.InstallationAvailable)
                        {
                            ccoModel.InstallationAvailable = true;
                        }
                        if (pr.InstallationSelected && region.InstallationPriceAvailable)
                        {
                            ccoModel.InstallationPrice += pr.InstallationPrice;
                        }
                    }
                    if (ccoModel.TransportAvailable)
                    {
                        ccoModel.TransportPrice = region.TransportPrice;
                        ccoModel.CargoPrice = 0;
                        ccoModel.CargoPrice2 = 0;
                        if (region.MinPriceRequired && ccoModel.SummaryCargo.CartTotalPrice < region.MinPrice && !ccoModel.BasketLocked)
                        {
                            ccoModel.Message10 = "<span class=\"checkOut-Error-Text\">Seçtiğiniz ürünlerden bazıları kargo ile gönderilemediğinden şirketimiz tarafından nakliye edilmesi gerekmektedir.";
                            ccoModel.Message10 += " " + ccoModel.CargoAddress.CityName + " iline nakliye yapılabilmesi için en az " + region.MinPrice.ToString("###,###,##0 TL") + "'lik alışveriş yapılması gerekmektedir.</span>";
                            ccoModel.AddressCompleted = 0;
                        }
                        else if (!region.MinPriceRequired && ccoModel.SummaryCargo.CartTotalPrice < region.MinPrice)
                        {
                            ccoModel.TransportPrice = region.TransportPriceUnderLimit;
                        }
                    }
                }
            }

            #endregion

            #region Fırsat ürünü var mı?
            ccoModel.OppoturnityProductsAvailable = (cartModel.Products.Where(o => o.OpportunityProduct).Count() > 0) ? true : false;
            #endregion

            ccoModel.CargoTotalPrice = ccoModel.CargoPrice + ccoModel.CargoPrice2;

            #endregion

            ccoModel.TotalPayment = ccoModel.CargoTotalPrice + ccoModel.TransportPrice + ccoModel.InstallationPrice + ccoModel.SummaryCargo.CartTotalPrice - voucherSUM;
            ccoModel.CampaignTotalPayment = ccoModel.SummaryCargo.CampaignCartTotalPrice;

            #region Calculate Price with Transfer

            ccoModel.TotalPaymentWithTransfer = 0;

            if (Parameters.UseTransferDiscount)
            {
                int HavaleHariciOdemeSayisi = ccoModel.VoucherList.Where(v => v.Selected == true && v.TypeId > 100 && v.TypeId != 120).Count();
                if (HavaleHariciOdemeSayisi == 0 && ccoModel.SummaryCargo.CartTotalPrice > 0)
                {
                    ccoModel.TotalPaymentWithTransfer = ccoModel.CargoTotalPrice + ccoModel.TransportPrice + ccoModel.InstallationPrice + ccoModel.SummaryCargo.CartTotalPriceTransfer + ccoModel.SummaryCargo.ListTotalPrice - voucherSUM;
                }
            }

            if (Parameters.CreditCardDiscount > 1)
            {
                ccoModel.TotalPaymentWithCreditCard = ccoModel.CargoTotalPrice + ccoModel.TransportPrice + ccoModel.InstallationPrice + ccoModel.SummaryCargo.CartTotalPriceCreditCard + ccoModel.SummaryCargo.ListTotalPrice - voucherSUM;
                ccoModel.CampaignTotalPaymentWithCreditCard = ccoModel.SummaryCargo.CampaignCartTotalPriceCreditCard;
            }

            #endregion

            #region Init Vars

            ccoModel.CardNumber1 = "";
            ccoModel.CardNumber2 = "";
            ccoModel.CardNumber3 = "";
            ccoModel.CardNumber4 = "";

            ccoModel.ValidMonth = 0;
            ccoModel.ValidYear = 0;
            ccoModel.CVV = "";
            ccoModel.CardOwnerName = "";
            ccoModel.PartialPayment = null;
            ccoModel.VisitorRegistered = false;
            ccoModel.AgreementChecked = 0;
            ccoModel.GuarantorNotSelectedAgreed = 0;

            var snPosList = dbPos.GetList().Where(o => o.PosVoucher == "S").FirstOrDefault();


            if (snPosList != null)
            {
                ccoModel.VoucherPosId = snPosList.PosId;
                snPosList.PosInstallment = dbPos.GetInstallmentList(snPosList.PosId, 1, 9999, 0, 0);
                ccoModel.VoucherRate = snPosList.PosInstallment != null ? snPosList.PosInstallment.Where(o => o.InstallmentNumber == 10).FirstOrDefault().CommissionRate : (1 + (Parameters.SenetEkUcret / 100));
            }
            if (Parameters.PosList.Where(w => w.PosVoucher == "S").Count() > 0)
            {
                ccoModel.PosInstallmentListVoucher = dbPos.GetInstallmentListPayment(Parameters.PosList.Where(w => w.PosVoucher == "S").FirstOrDefault().PosId, ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard - ccoModel.CargoTotalPrice : ccoModel.SummaryCargo.CartTotalPrice, ccoModel.SummaryCargo.CartTotalPrice, ccoModel.CampaignTotalPaymentWithCreditCard > 0 ? ccoModel.CampaignTotalPaymentWithCreditCard : ccoModel.CampaignTotalPayment, ccoModel.CampaignTotalPayment, ccoModel.CargoPrice, ccoModel.CargoPrice2);
            }


            #region Kimlik Bilgileri

            if (eStoreUser.AccountType != 1)
            {
                //ziyaretçi değil ise
                ccoModel.Kimlik = new Nufus();
                ccoModel.Kimlik = dbAccount.GetUserIdentity(eStoreUser.AccountId);
                if (ccoModel.Kimlik == null)
                {
                    ccoModel.Kimlik = new Nufus();
                }
            }
            else
            {
                ccoModel.Kimlik = new Nufus();
            }

            if (ccoModel.Kimlik.DogumTarihi.Year.ToString() != "1")
            {
                ccoModel.Kimlik.BirthDayNumber = ccoModel.Kimlik.DogumTarihi.Day.ToString();
                ccoModel.Kimlik.BirthMonth = ccoModel.Kimlik.DogumTarihi.Month.ToString();
                ccoModel.Kimlik.BirthYear = ccoModel.Kimlik.DogumTarihi.Year.ToString();
            }
            else
            {
                ccoModel.Kimlik.BirthDayNumber = "";
                ccoModel.Kimlik.BirthMonth = "";
                ccoModel.Kimlik.BirthYear = "";
            }
            ccoModel.Kimlik.FirstName = eStoreUser.FirstName;
            ccoModel.Kimlik.LastName = eStoreUser.LastName;

            #endregion

            #endregion

            #region POS & Installment

            ccoModel.PosList = Parameters.PosListDDL; // dbPos.GetList();
            if (ccoModel.SelectedPos > 0)
            {
                ccoModel.PosInstallmentList = dbPos.GetInstallmentListPayment(ccoModel.SelectedPos, ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard - ccoModel.CargoTotalPrice : ccoModel.SummaryCargo.CartTotalPrice, ccoModel.SummaryCargo.CartTotalPrice, ccoModel.CampaignTotalPaymentWithCreditCard, ccoModel.CampaignTotalPayment, ccoModel.CargoPrice, ccoModel.CargoPrice2);
            }
            else
            {
                ccoModel.PosInstallmentList = new List<PosInstallment>();
            }

            ccoModel.BinList = Parameters.BinList;

            #endregion

            #region Bank

            ccoModel.BankList = Parameters.BankList;
            //ccoModel.BankList.Add(new Bank() { BankName = "Seçiniz", BankId = 0 });
            //ccoModel.BankList = ccoModel.BankList.OrderBy(o => o.BankId).ToList();

            #endregion

            return ccoModel;
        }

        #endregion

        #region Get_ccoModel with Parameter

        private CartCheckOutModel Get_ccoModel(CartCheckOutModel ccoTempModel)
        {
            var ccoModel = Get_ccoModel();

            ccoModel.UserId = eStoreUser.AccountId;
            ccoModel.AddressCompleted = ccoTempModel.AddressCompleted;
            ccoModel.AgreementChecked = ccoTempModel.AgreementChecked;
            ccoModel.GuarantorNotSelectedAgreed = ccoTempModel.GuarantorNotSelectedAgreed;
            CartModel cartModel = new CartModel();
            cartModel.Products = dbCart.GetList(eStoreUser.AccountId, eStoreUser.AccountType);

            #region Ürün stok kontrolü
            decimal toplamDesi = 0;
            bool freeAvailable = false;
            foreach (Cart cart in cartModel.Products)
            {
                Product product = dbProduct.Get(cart.ProductId, eStoreUser.AccountId);
                var productStock = product.InStockDepo;
                var productInCart = (int)cart.Qty;
                var productInCartExtra = productInCart - productStock;
                var productToCartAvailable = productStock - productInCart;
                toplamDesi += product.Desi;
                if (productStock < 1 && product.CheckStock && !Parameters.AllowEndedProducts)
                {
                    ccoModel.Message9 = "<span class=\"checkOut-Error-Text\">\"" + product.ProductName + "\" ürününden stoklarımızda hiç kalmadı. Sepetinize giderek bu ürünü sepetten çıkartmanız gerekmektedir.</span>";
                }
                else if (productInCart > productStock && product.CheckStock && !Parameters.AllowEndedProducts)
                {
                    ccoModel.Message9 = "<span class=\"checkOut-Error-Text\">\"" + product.ProductName + "\" ürününden stoklarımızda " + (Convert.ToInt32(productStock)).ToString() + " adet kaldı. Sepetinize giderek bu üründen " + (Convert.ToInt32(productInCartExtra)).ToString() + " adet eksiltmeniz gerekmektedir.</span>";
                }

                if (product.FreeCargo)
                {
                    freeAvailable = true;
                }
            }
            #region taksit sayısı

            ccoModel.MaxInstallmentCount = 9999;
            foreach (Cart cart in cartModel.Products)
            {
                if (cart.MaxInstallmentCount <= ccoModel.MaxInstallmentCount && cart.MaxInstallmentCount > 0)
                {
                    ccoModel.MaxInstallmentCount = cart.MaxInstallmentCount;
                }
            }

            #endregion
            //Mesaj
            //dataOK = false;
            //ccoModel.Message9 = "<font color=red>Teslimat ve fatura adres bilgilerini kontrol ediniz.</font>";
            #endregion

            #region Seçili olmayan Hediye Çekleri ve Ara Ödemeler UnSelected Yapılır

            foreach (Voucher voucherTemp in ccoTempModel.VoucherList)
            {
                if (!voucherTemp.Selected)
                {
                    Voucher voucher = ccoModel.VoucherList.Where(v => v.VoucherId == voucherTemp.VoucherId).FirstOrDefault();
                    if (voucher != null)
                    {
                        voucher.Selected = false;
                    }
                }
            }

            var voucherSUM = ccoModel.VoucherList.Where(v => v.Selected == true).Sum(i => i.Payment);

            #endregion

            #region Form Fields to New ccoModel !!!!

            ccoModel.PromoCode = ccoTempModel.PromoCode;
            ccoModel.Use3D = ccoTempModel.Use3D;
            ccoModel.IsTotalPayment = ccoTempModel.IsTotalPayment;
            ccoModel.OtherInstallment = ccoTempModel.OtherInstallment;

            ccoModel.FirstName = ccoTempModel.FirstName;
            ccoModel.LastName = ccoTempModel.LastName;
            ccoModel.Email = ccoTempModel.Email;
            ccoModel.Mobile = ccoTempModel.Mobile;
            ccoModel.VisitorRegistered = ccoTempModel.VisitorRegistered;

            if (ccoTempModel.PartialPayment.HasValue)
            {
                ccoModel.PartialPayment = ccoTempModel.PartialPayment;
            }

            if (ccoModel.CargoAddresses.Count > 1)
            {
                ccoModel.CargoAddressId = ccoTempModel.CargoAddressId;
                ccoModel.InvoiceAddressId = ccoTempModel.InvoiceAddressId;

                ccoModel.CargoAddress = dbAddress.Get(eStoreUser.AccountId, ccoModel.CargoAddressId);
                ccoModel.InvoiceAddress = dbAddress.Get(eStoreUser.AccountId, ccoModel.InvoiceAddressId);
            }

            if (ccoModel.GuarantorList.Count() > 0)
            {
                ccoModel.Guarantor1Id = ccoTempModel.Guarantor1Id;
                ccoModel.Guarantor1 = eStoreUser.AccountType == 0 ? dbAccount.GetGuarantor(ccoTempModel.Guarantor1Id) : dbAccount.GetVisitorGuarantor(ccoTempModel.Guarantor1Id);
                ccoModel.Guarantor2Id = ccoTempModel.Guarantor2Id;
                ccoModel.Guarantor2 = eStoreUser.AccountType == 0 ? dbAccount.GetGuarantor(ccoTempModel.Guarantor2Id) : dbAccount.GetVisitorGuarantor(ccoTempModel.Guarantor2Id);
            }
            if (ccoTempModel.Kimlik != null)
            {
                ccoModel.Kimlik = ccoTempModel.Kimlik;
                ccoModel.Kimlik.BirthDayNumber = ccoTempModel.Kimlik.BirthDayNumber;
                ccoModel.Kimlik.BirthMonth = ccoTempModel.Kimlik.BirthMonth;
                ccoModel.Kimlik.BirthYear = ccoTempModel.Kimlik.BirthYear;
            }
            else
            {
                if (eStoreUser.AccountType != 1)
                {
                    ccoModel.Kimlik = dbAccount.GetUserIdentity(eStoreUser.AccountId);
                }
                if (ccoModel.Kimlik != null)
                {
                    ccoModel.Kimlik.FirstName = eStoreUser.FirstName;
                    ccoModel.Kimlik.LastName = eStoreUser.LastName;
                    if (ccoModel.Kimlik.DogumTarihi.Year.ToString() != "1")
                    {
                        ccoModel.Kimlik.BirthDayNumber = ccoModel.Kimlik.DogumTarihi.Day.ToString();
                        ccoModel.Kimlik.BirthMonth = ccoModel.Kimlik.DogumTarihi.Month.ToString();
                        ccoModel.Kimlik.BirthYear = ccoModel.Kimlik.DogumTarihi.Year.ToString();
                    }
                    else
                    {
                        ccoModel.Kimlik.BirthDayNumber = "";
                        ccoModel.Kimlik.BirthMonth = "";
                        ccoModel.Kimlik.BirthYear = "";
                    }
                }
                else
                {
                    ccoModel.Kimlik = new Nufus();
                    ccoModel.Kimlik.FirstName = eStoreUser.FirstName;
                    ccoModel.Kimlik.LastName = eStoreUser.LastName;
                    ccoModel.Kimlik.BirthDayNumber = "";
                    ccoModel.Kimlik.BirthMonth = "";
                    ccoModel.Kimlik.BirthYear = "";
                }
            }


            #region Senet Şehir Kontrolü

            IList<City> VoucherCities = Parameters.CityList;
            //adres seçilmiş
            if (VoucherCities.Where(o => o.VoucherPayment == true).Select(o => o.CityId).Contains(ccoModel.CargoAddress.City))
            {
                ccoModel.VoucherAvailable = 1;
            }
            else
            {
                ccoModel.VoucherAvailable = 0;
            }

            #endregion

            ccoModel.CargoWithInvoice = ccoTempModel.CargoWithInvoice;

            #region Credit Card Info

            ccoModel.CardNumber1 = ccoTempModel.CardNumber1;
            ccoModel.CardNumber2 = ccoTempModel.CardNumber2;
            ccoModel.CardNumber3 = ccoTempModel.CardNumber3;
            ccoModel.CardNumber4 = ccoTempModel.CardNumber4;

            ccoModel.ValidMonth = ccoTempModel.ValidMonth;
            ccoModel.ValidYear = ccoTempModel.ValidYear;
            ccoModel.CVV = ccoTempModel.CVV;
            ccoModel.CardOwnerName = ccoTempModel.CardOwnerName;

            #endregion

            ccoModel.PaymentType = ccoTempModel.PaymentType;
            ccoModel.SelectedPos = ccoTempModel.SelectedPos;
            ccoModel.SelectedInstallment = ccoTempModel.SelectedInstallment;
            ccoModel.SelectedCargoCompanyId = ccoTempModel.SelectedCargoCompanyId;

            ccoModel.SelectedBank = ccoTempModel.SelectedBank;

            ccoModel.OrderNote = ccoTempModel.OrderNote;

            ccoModel.OtherInstallment = ccoTempModel.OtherInstallment;
            ccoModel.OtherNameSurname = ccoTempModel.OtherNameSurname;
            ccoModel.OtherTcKimlikNo = ccoTempModel.OtherTcKimlikNo;
            ccoModel.OtherMonthlyIncoming = ccoTempModel.OtherMonthlyIncoming;
            ccoModel.OtherFatherName = ccoTempModel.OtherFatherName;
            ccoModel.OtherMotherName = ccoTempModel.OtherMotherName;

            #endregion

            var PosVoucherType = ccoModel.PaymentType == PaymentTypes.SenetleOdeme ? "S" : "P";
            if (ccoModel.PaymentType == PaymentTypes.SenetleOdeme)
            {
                ccoModel.PosList = ccoModel.PosList.Where(o => o.PosVoucher == "S").ToList();
            }
            else if (ccoModel.PaymentType == PaymentTypes.AnindaKrediOdeme)
            {
                ccoModel.PosList = ccoModel.PosList.Where(o => o.PosVoucher == "AK").ToList();
            }
            else
            {
                ccoModel.PosList = ccoModel.PosList.Where(o => o.PosVoucher == "P" || o.PosVoucher == "" || o.PosVoucher == null).ToList();
            }
            if (!ccoModel.PosList.Select(o => o.PosId).Contains(ccoModel.SelectedPos))
            {
                ccoModel.SelectedPos = ccoModel.PosList.Count() > 0 ? ccoModel.PosList.FirstOrDefault().PosId : 0;
            }

            #region Cargo & Transport & TotalPayment

            #region Şehiriçi ücretsiz kargo kontrolü

            IList<CityDDL> Cities = dbCity.GetFreeCargoCities();
            var freeCargoInCityProductAvailable = false;
            foreach (Cart cart in cartModel.Products)
            {
                Product product = dbProduct.Get(cart.ProductId, eStoreUser.AccountId);
                if (product.FreeCargoInCity)
                {
                    freeCargoInCityProductAvailable = true;
                    break;
                }
            }
            if (freeCargoInCityProductAvailable && Cities.Any(x => x.CityName == ccoModel.CargoAddress.CityName))
            {
                ccoModel.FreeCargoInCityAvailable = true;
                ccoModel.SelectedCargoCompanyId = ccoModel.CargoList.Where(c => c.OnlyFreeCargoInCity).FirstOrDefault().CargoId;
            }
            else
            {
                ccoModel.FreeCargoInCityAvailable = false;
                ccoModel.SelectedCargoCompanyId = ccoModel.CargoList.Where(c => c.OnlyFreeCargoInCity == false).FirstOrDefault().CargoId;
            }
            #endregion

            #region Kargo ücreti getir
            ccoModel.SummaryCargo = dbCart.GetSummaryCargo(eStoreUser.AccountId, eStoreUser.AccountType, ccoModel.SelectedCargoCompanyId, ccoModel.CargoAddress == null ? (short)0 : ccoModel.CargoAddress.City, Parameters.CreditCardDiscount, Parameters.TransferDiscount, Parameters.CargoCalculateForSameProduct);

            ccoModel.CargoPrice = 0;
            ccoModel.CargoPrice2 = 0;

            if (ccoModel.SummaryCargo != null)
            {
                if (ccoModel.SummaryCargo.CartItemCount > 0)
                {
                    ccoModel.CargoPrice = Math.Round(ccoModel.SummaryCargo.CartCargoPrice * (Parameters.SetCargoPricesWithoutTax ? 1 : Parameters.CargoList.Where(c => c.CargoId == ccoModel.SelectedCargoCompanyId).FirstOrDefault().Tax), 2);
                }

                if (ccoModel.SummaryCargo.ListItemCount > 0)
                {
                    ccoModel.CargoPrice2 = Math.Round(ccoModel.SummaryCargo.ListCargoPrice * (Parameters.SetCargoPricesWithoutTax ? 1 : Parameters.ListCargoProductTax), 2);
                }
            }
            #endregion

            #region Tek Kargo (Sabit Kargo)

            if (Parameters.OnlyOneCargoPrice > 0 && !freeAvailable)
            {
                ccoModel.CargoPrice = Parameters.OnlyOneCargoPrice;
            }
            #endregion

            #region Cargo Min Limit Control "X TL Üzeri Y TL (2031-2032)"

            if (Parameters.CargoMinLimit > 0 && ccoModel.SummaryCargo.CartTotalPriceCreditCard > Parameters.CargoMinLimit && ccoModel.CargoPrice > Parameters.CargoMinLimitPrice)
            {
                ccoModel.CargoPrice = Parameters.CargoMinLimitPrice;
            }

            #endregion

            #region Cargo Free Limit Control (Ref2015)

            if (Parameters.CargoLimit > 0 && ccoModel.SummaryCargo.CartTotalPriceCreditCard > Parameters.CargoLimit)
            {
                ccoModel.CargoPrice = 0;
                ccoModel.CargoPrice2 = 0;
            }

            #endregion

            #region Ücretsiz Kargo Varsa Tümünü Ücretsiz Yap

            if (ccoModel.CargoPrice > 0 && toplamDesi <= Parameters.FreeCargoDesiLimit)
            {
                var freeCargoProductAvailable = false;
                foreach (Cart cart in cartModel.Products)
                {
                    Product product = dbProduct.Get(cart.ProductId, eStoreUser.AccountId);
                    if (product.FreeCargo)
                    {
                        freeCargoProductAvailable = true;
                        break;
                    }
                }
                if (freeCargoProductAvailable)
                {
                    ccoModel.CargoPrice = 0;
                }
            }

            #endregion

            #region farklı fatura adresi
            if (ccoModel.CargoAddressId != ccoModel.InvoiceAddressId && ccoModel.CargoWithInvoice == false)
            {
                ccoModel.CargoInvoicePrice = dbCargoRange.GetRangePrice(eStoreUser.AccountId, ccoModel.SelectedCargoCompanyId, 0).Price;
                ccoModel.CargoPrice = ccoModel.CargoPrice + Math.Round(ccoModel.CargoInvoicePrice * Parameters.CargoList.Where(c => c.CargoId == ccoModel.SelectedCargoCompanyId).FirstOrDefault().Tax, 2);
            }
            #endregion

            #region kapıda ödeme
            if (ccoModel.PaymentType == PaymentTypes.KapidaOdeme)
            {
                ccoModel.CargoPrice = ccoModel.CargoPrice + Parameters.AdditionFeeForPaymentAtDoor;  // Kapıda Ödeme Ek İşlem Ücreti
            }
            #endregion

            #region Nakliye ve Montaj

            if (Parameters.CityList.Where(o => o.CityId == ccoModel.CargoAddress.City).Count() > 0)
            {
                var regionId = Parameters.CityList.Where(c => c.CityId == ccoModel.CargoAddress.City).FirstOrDefault().RegionId;
                if (regionId > 0)
                {
                    var region = Parameters.RegionList.Where(r => r.Id == regionId).FirstOrDefault();
                    foreach (var pr in cartModel.Products)
                    {
                        if (pr.TransportNeeded)
                        {
                            ccoModel.TransportAvailable = true;
                        }
                        if (pr.InstallationSelected && region.InstallationAvailable)
                        {
                            ccoModel.InstallationAvailable = true;
                        }
                    }
                    if (ccoModel.TransportAvailable)
                    {
                        ccoModel.TransportPrice = region.TransportPrice;
                        ccoModel.CargoPrice = 0;
                        ccoModel.CargoPrice2 = 0;
                        if (region.MinPriceRequired && ccoModel.SummaryCargo.CartTotalPrice < region.MinPrice && !ccoModel.BasketLocked)
                        {
                            ccoModel.Message10 = "<span class=\"checkOut-Error-Text\">Seçtiğiniz ürünlerden bazıları kargo ile gönderilemediğinden şirketimiz tarafından nakliye edilmesi gerekmektedir.";
                            ccoModel.Message10 += " " + ccoModel.CargoAddress.CityName + " iline nakliye yapılabilmesi için en az " + region.MinPrice.ToString("###,###,##0 TL") + "'lik alışveriş yapılması gerekmektedir.</span>";
                            ccoModel.AddressCompleted = 0;
                        }
                        else if (!region.MinPriceRequired && ccoModel.SummaryCargo.CartTotalPrice < region.MinPrice)
                        {
                            ccoModel.TransportPrice = region.TransportPriceUnderLimit;
                        }
                    }
                }
            }

            #endregion




            ccoModel.CargoTotalPrice = ccoModel.CargoPrice + ccoModel.CargoPrice2;

            ccoModel.TotalPayment = ccoModel.CargoTotalPrice + ccoModel.TransportPrice + ccoModel.InstallationPrice + ccoModel.SummaryCargo.CartTotalPrice - voucherSUM;

            #region Calculate Price with Transfer

            ccoModel.TotalPaymentWithTransfer = 0;
            ccoModel.TotalPaymentWithCreditCard = 0;

            if (Parameters.UseTransferDiscount)
            {
                int HavaleHariciOdemeSayisi = ccoModel.VoucherList.Where(v => v.Selected == true && v.TypeId > 100 && v.TypeId != 120).Count();
                if (HavaleHariciOdemeSayisi == 0 && ccoModel.SummaryCargo.CartTotalPrice > 0)
                {
                    ccoModel.TotalPaymentWithTransfer = ccoModel.CargoTotalPrice + ccoModel.TransportPrice + ccoModel.InstallationPrice + ccoModel.SummaryCargo.CartTotalPriceTransfer + ccoModel.SummaryCargo.ListTotalPrice - voucherSUM;
                }
            }

            if (Parameters.CreditCardDiscount > 1)
            {
                ccoModel.TotalPaymentWithCreditCard = ccoModel.CargoTotalPrice + ccoModel.TransportPrice + ccoModel.InstallationPrice + ccoModel.SummaryCargo.CartTotalPriceCreditCard + ccoModel.SummaryCargo.ListTotalPrice - voucherSUM;
            }

            #endregion

            #endregion


            #region POS & Installment

            if (ccoModel.SelectedPos > 0)
            {
#warning PartialPayment yapılacak
                ccoModel.PosInstallmentList = dbPos.GetInstallmentListPayment(ccoModel.SelectedPos, ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard - ccoModel.CargoTotalPrice : ccoModel.SummaryCargo.CartTotalPrice, ccoModel.SummaryCargo.CartTotalPrice, ccoModel.CampaignTotalPaymentWithCreditCard > 0 ? ccoModel.CampaignTotalPaymentWithCreditCard : ccoModel.CampaignTotalPayment, ccoModel.CampaignTotalPayment, ccoModel.CargoPrice, ccoModel.CargoPrice2);
                ccoModel.SelectedPosDescription = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Description;
                ccoModel.SelectedPosEnabled3D = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Enabled3D;
            }
            else
            {
                ccoModel.PosInstallmentList = new List<PosInstallment>();
                ccoModel.SelectedPosDescription = "";
                ccoModel.SelectedPosEnabled3D = false;
            }

            #endregion

            #region Type3D
            ccoModel.Type3D = ccoModel.PosList.Count() > 0 ? ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Type3D : "Yok";
            if (ccoModel.Type3D == "Zorunlu")
            {
                ccoModel.Use3D = true;
            }
            else if (ccoModel.Type3D == "Yok")
            {
                ccoModel.Use3D = false;
            }
            #endregion

            return ccoModel;
        }

        #endregion

        #region Refresh Checkout

        [Child]
        public ActionResult Refresh(CartCheckOutModel ccoTempModel)
        {
            if (!Parameters.AllowVisitorsToUsingCart && eStoreUser.AccountType == 1)
            {
                string url = "/Account/Login?ReturnUrl=/Cart/Checkout";
                return Redirect(url);
            }
            var ccoModel = Get_ccoModel(ccoTempModel);
            bool PaymentSucceeded = false;
            decimal Payment = 0;
            long PaymentId = 0;
            bool dataOK = true;
            decimal HavaleEFTIndirimi = 1;
            decimal KrediKartIndirimi = 1;
            decimal KomisyonOrani = 1;
            decimal KampanyaKomisyonOrani = 1;
            string OrderPaymentType = "";
            ccoModel.AddressCompleted = ccoTempModel.AddressCompleted;

            if (Parameters.OnlyUseCCandMTforOpportunityProduct && ccoModel.OppoturnityProductsAvailable && (ccoModel.PaymentType != PaymentTypes.KrediKart && ccoModel.PaymentType != PaymentTypes.HavaleEft))
            {
                dataOK = false;
                ccoModel.PaymentType = PaymentTypes.KrediKart;
                ccoModel.Message5 = "<span class=\"checkOut-Error-Text\">Sepetinizde fırsat ürünleri bulunmaktadır, sadece kredi kartı ya da havale ile ödeme yapabilirsiniz.</span>";
            }

            if (eStoreUser.AccountType == 1 && !ccoModel.VisitorRegistered)
            {
                Account account = dbAccount.Get(ccoModel.Email);
                if (string.IsNullOrEmpty(ccoModel.FirstName) || string.IsNullOrEmpty(ccoModel.LastName) || string.IsNullOrEmpty(ccoModel.Email))
                {
                    dataOK = false;
                    ccoModel.Message6 = "<span class=\"checkOut-Error-Text\">Kişisel bilgilerinizi girmediniz.</span>";
                    ccoModel.AddressCompleted = 0;
                }
                else if (account != null)
                {
                    dataOK = false;
                    ccoModel.Message6 = "<span class=\"checkOut-Error-Text\">Bu bilgilerle zaten kayıt olunmuş. <a href=\"/Account/RemindPassword\" target=\"_blank\">Şifrenizi mi unuttunuz?</a></span>";
                    ccoModel.AddressCompleted = 0;
                }

                //burada bir de girilen e-mail'e bağlı hesap varmı diye bakacağız. eğer varsa giriş yapmasını önereceğiz.
            }
            if (Parameters.CheckOutTCKNRequired && string.IsNullOrEmpty(ccoModel.InvoiceAddress.TaxNo))
            {
                dataOK = false;
                ccoModel.Message12 = "<span class=\"checkOut-Error-Text\">Alışverişe devam edebilmek için Fatura Adresinizdeki TC Kimlik No alanını doldurmalısınız.</span>";
                ccoModel.AddressCompleted = 0;
            }

            #region Senet için adres kontrol et

            if (ccoTempModel.PaymentType == PaymentTypes.SenetleOdeme)
            {
                IList<City> Cities = Parameters.CityList;
                if (ccoTempModel.CargoAddress != null)
                {
                    //adres seçilmiş
                    if (Cities.Where(o => o.VoucherPayment == true).Select(o => o.CityId).Contains(ccoModel.CargoAddress.City))
                    {
                        ccoModel.VoucherAvailable = 1;
                    }
                    else
                    {
                        dataOK = false;
                        ccoModel.VoucherAvailable = 0;
                        ccoModel.Message8 = "<span class=\"checkOut-Error-Text\">Bulunduğunuz şehir, senetli ödeme için uygun değildir.</span>";
                    }
                }
                else
                {
                    dataOK = false;
                    ccoModel.VoucherAvailable = 0;
                    ccoModel.Message8 = "<span class=\"checkOut-Error-Text\">Bulunduğunuz şehir, senetli ödeme için uygun değildir.</span>";
                    //adres seçilmemiş
                }

                if (ccoModel.PosInstallmentList.Where(t => t.InstallmentNumber == ccoModel.SelectedInstallment).Count() <= 0)
                {
                    ccoModel.SelectedInstallment = 0; //ccoModel.PosInstallmentList.FirstOrDefault().InstallmentNumber;
                }
                var firstInstallment = ccoModel.PosInstallmentList.FirstOrDefault().InstallmentNumber;

                PosInstallment pt = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == (ccoModel.SelectedInstallment <= 0 ? firstInstallment : ccoModel.SelectedInstallment)).ToArray<PosInstallment>().FirstOrDefault();


                if (pt.TotalInterestPrice < pt.Limit)
                {
                    dataOK = false;
                    ccoModel.Message7 = "<span class=\"checkOut-Error-Text\">Senetli ödeme seçeneğini kullanırken " + pt.InstallmentNumber + " taksitli ödeme yapmak için en az " + pt.Limit.ToString("###,###,##0") + " TL'lik alışveriş yapmanız gerekmektedir.</span>";
                }

            }

            #endregion

            #region Ürün stok kontrolü
            CartModel cartModel = new CartModel();
            cartModel.Products = dbCart.GetList(eStoreUser.AccountId, eStoreUser.AccountType);

            foreach (Cart cart in cartModel.Products)
            {
                Product product = dbProduct.Get(cart.ProductId, eStoreUser.AccountId);
                var productStock = product.InStockDepo;
                var productInCart = (int)cart.Qty;
                var productInCartExtra = productInCart - productStock;
                var productToCartAvailable = productStock - productInCart;
                if (productStock < 1 && product.CheckStock && !Parameters.AllowEndedProducts)
                {
                    dataOK = false;
                    ccoModel.Message9 = "<span class=\"checkOut-Error-Text\">\"" + product.ProductName + "\" ürününden stoklarımızda hiç kalmadı. Sepetinize giderek bu ürünü sepetten çıkartmanız gerekmektedir.</span>";
                }
                else if (productInCart > productStock && product.CheckStock && !Parameters.AllowEndedProducts)
                {
                    dataOK = false;
                    ccoModel.Message9 = "<span class=\"checkOut-Error-Text\">\"" + product.ProductName + "\" ürününden stoklarımızda " + (Convert.ToInt32(productStock)).ToString() + " adet kaldı. Sepetinize giderek bu üründen " + (Convert.ToInt32(productInCartExtra)).ToString() + " adet eksiltmeniz gerekmektedir.</span>";
                }
            }
            //Mesaj
            //dataOK = false;
            //ccoModel.Message9 = "<font color=red>Teslimat ve fatura adres bilgilerini kontrol ediniz.</font>";
            #endregion

            #region Nakliye ve Montaj

            if (Parameters.CityList.Where(o => o.CityId == ccoModel.CargoAddress.City).Count() > 0)
            {
                var regionId = Parameters.CityList.Where(c => c.CityId == ccoModel.CargoAddress.City).FirstOrDefault().RegionId;
                if (regionId > 0)
                {
                    var region = Parameters.RegionList.Where(r => r.Id == regionId).FirstOrDefault();
                    foreach (var pr in cartModel.Products)
                    {
                        if (pr.TransportNeeded)
                        {
                            ccoModel.TransportAvailable = true;
                        }
                        if (pr.InstallationSelected && region.InstallationAvailable)
                        {
                            ccoModel.InstallationAvailable = true;
                        }
                    }
                    if (ccoModel.TransportAvailable)
                    {
                        ccoModel.TransportPrice = region.TransportPrice;
                        ccoModel.CargoPrice = 0;
                        ccoModel.CargoPrice2 = 0;
                        if (region.MinPriceRequired && ccoModel.SummaryCargo.CartTotalPrice < region.MinPrice && !ccoModel.BasketLocked)
                        {
                            ccoModel.Message10 = "<span class=\"checkOut-Error-Text\">Seçtiğiniz ürünlerden bazıları kargo ile gönderilemediğinden şirketimiz tarafından nakliye edilmesi gerekmektedir.";
                            ccoModel.Message10 += " " + ccoModel.CargoAddress.CityName + " iline nakliye yapılabilmesi için en az " + region.MinPrice.ToString("###,###,##0 TL") + "'lik alışveriş yapılması gerekmektedir.</span>";
                            ccoModel.AddressCompleted = 0;
                            dataOK = false;
                        }
                        else if (!region.MinPriceRequired && ccoModel.SummaryCargo.CartTotalPrice < region.MinPrice)
                        {
                            ccoModel.TransportPrice = region.TransportPriceUnderLimit;
                        }
                    }
                }
            }

            #endregion

            #region Ödeme Yapılmak İsteniyorsa Adres Kontrolü (Kendi ürünü varsa)

            if (!string.IsNullOrEmpty(ccoTempModel.SelectedAction) && ccoModel.SummaryCargo.CartItemCount > 0)
            {
                if (ccoTempModel.CargoAddressId == 0 || ccoTempModel.InvoiceAddressId == 0)
                {
                    dataOK = false;
                    ccoModel.Message2 = "<span class=\"checkOut-Error-Text\">Teslimat ve fatura adres bilgilerini kontrol ediniz.</span>";
                }
            }

            #endregion

            #region Prepare Contract Price

            if (ccoModel.PaymentType == PaymentTypes.KrediKart)
            {
                if (ccoModel.SelectedInstallment == 0)
                {
                    ccoModel.SelectedInstallment = 1;
                }
                if (ccoModel.SelectedPos == 0)
                {
                    ccoModel.ContractTotalPrice = ccoModel.CampaignTotalPaymentWithCreditCard > 0 ? ccoModel.CampaignTotalPaymentWithCreditCard : (ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard : ccoModel.TotalPayment);
                }
                else
                {
                    PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                    if (pi == null)
                    {
                        ccoModel.SelectedInstallment = 1;
                        pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                    }
                    if (pi != null)
                    {
                        ccoModel.ContractTotalPrice = pi.CampaignTotalInterestPrice > 0 ? pi.CampaignTotalInterestPrice : pi.TotalInterestPrice;
                    }
                    else
                    {
                        ccoModel.ContractTotalPrice = ccoModel.CampaignTotalPaymentWithCreditCard > 0 ? ccoModel.CampaignTotalPaymentWithCreditCard : ccoModel.TotalPaymentWithCreditCard;
                    }
                }
            }
            else if (ccoModel.PaymentType == PaymentTypes.HavaleEft)
            {
                ccoModel.ContractTotalPrice = ccoModel.TotalPaymentWithTransfer > 0 ? ccoModel.TotalPaymentWithTransfer : ccoModel.TotalPayment;
            }
            else if (ccoModel.PaymentType == PaymentTypes.KapidaOdeme)
            {
                ccoModel.ContractTotalPrice = ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard : ccoModel.TotalPayment;
            }
            else if (ccoModel.PaymentType == PaymentTypes.SenetleOdeme)
            {
                if (ccoModel.SelectedInstallment == 0)
                {
                    //ccoModel.SelectedInstallment = ccoModel.PosInstallmentList.FirstOrDefault().InstallmentNumber;
                }
                if (ccoModel.SelectedPos == 0)
                {
                    ccoModel.ContractTotalPrice = ccoModel.CampaignTotalPaymentWithCreditCard > 0 ? ccoModel.CampaignTotalPaymentWithCreditCard : (ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard : ccoModel.TotalPayment);
                }
                else
                {
                    if (ccoModel.SelectedInstallment > 0)
                    {
                        PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                        if (pi == null)
                        {
                            //ccoModel.SelectedInstallment = ccoModel.PosInstallmentList.FirstOrDefault().InstallmentNumber;
                            pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                        }
                        if (pi != null)
                        {
                            ccoModel.ContractTotalPrice = pi.CampaignTotalInterestPrice > 0 ? pi.CampaignTotalInterestPrice : pi.TotalInterestPrice;
                        }
                        else
                        {
                            ccoModel.ContractTotalPrice = ccoModel.CampaignTotalPayment > 0 ? ccoModel.CampaignTotalPayment : ccoModel.TotalPayment;
                        }
                    }
                    else
                    {
                        ccoModel.ContractTotalPrice = ccoModel.CampaignTotalPayment > 0 ? ccoModel.CampaignTotalPayment : ccoModel.TotalPayment;
                    }
                }
            }
            else if (ccoModel.PaymentType == PaymentTypes.AnindaKrediOdeme)
            {
                if (ccoModel.SelectedInstallment == 0)
                {
                    //ccoModel.SelectedInstallment = ccoModel.PosInstallmentList.FirstOrDefault().InstallmentNumber;
                }
                if (ccoModel.SelectedPos == 0)
                {
                    ccoModel.ContractTotalPrice = ccoModel.CampaignTotalPaymentWithCreditCard > 0 ? ccoModel.CampaignTotalPaymentWithCreditCard : (ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard : ccoModel.TotalPayment);
                }
                else
                {
                    if (ccoModel.SelectedInstallment > 0)
                    {
                        PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                        if (pi == null)
                        {
                            //ccoModel.SelectedInstallment = ccoModel.PosInstallmentList.FirstOrDefault().InstallmentNumber;
                            pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                        }
                        if (pi != null)
                        {
                            ccoModel.ContractTotalPrice = pi.CampaignTotalInterestPrice > 0 ? pi.CampaignTotalInterestPrice : pi.TotalInterestPrice;
                        }
                        else
                        {
                            ccoModel.ContractTotalPrice = ccoModel.CampaignTotalPayment > 0 ? ccoModel.CampaignTotalPayment : ccoModel.TotalPayment;
                        }
                    }
                    else
                    {
                        ccoModel.ContractTotalPrice = ccoModel.CampaignTotalPayment > 0 ? ccoModel.CampaignTotalPayment : ccoModel.TotalPayment;
                    }
                }
            }

            #endregion

            string VoucherComment = "";
            string OrderComment = "";

            if (!string.IsNullOrEmpty(ccoModel.PromoCode))
            {
                OrderComment = "PromoCode: (" + ccoModel.PromoCode + ") ";
                VoucherComment = "PromoCode: (" + ccoModel.PromoCode + ") ";
            }
            if (!string.IsNullOrEmpty(eStoreUser.UTMReferral))
            {
                OrderComment = OrderComment + " UTM : (" + eStoreUser.UTMReferral + ") ";
                VoucherComment = VoucherComment + " UTM : (" + eStoreUser.UTMReferral + ") ";
            }
            if (!string.IsNullOrEmpty(ccoModel.OrderNote))
            {
                OrderComment = OrderComment + " Sipariş Notu : (" + ccoModel.OrderNote + ") ";
                VoucherComment = VoucherComment + " Sipariş Notu : (" + ccoModel.OrderNote + ") ";
            }

            if (ccoTempModel.SelectedAction == "110" || ccoTempModel.SelectedAction == "KrediKart")
            {
                ccoTempModel.SelectedAction = "110";
                OrderPaymentType = "K";

                #region Payment Type - Credit Card

                #region Is Data OK


                var CardType = !string.IsNullOrEmpty(ccoModel.CardNumber1) ? ccoModel.CardNumber1.Substring(0, 1) : "";
                if (CardType == "3")
                {
                    ccoModel.CardNumber = ccoModel.CardNumber1 + ccoModel.CardNumber2 + ccoModel.CardNumber3;
                }
                else
                {
                    ccoModel.CardNumber = ccoModel.CardNumber1 + ccoModel.CardNumber2 + ccoModel.CardNumber3 + ccoModel.CardNumber4;
                }

                long cardNumber = 0;
                string cvv = "0";
                try
                {
                    cardNumber = long.Parse(ccoModel.CardNumber);
                }
                catch
                {
                    cardNumber = 0;
                }
                try
                {
                    cvv = ccoModel.CVV;
                }
                catch
                {
                    cvv = "0";
                }

                cvv = ccoModel.CVV;

                /*Bin Str*/
                var BinSTR = "";
                if (ccoModel.CardNumber.Length >= 15)
                {
                    BinSTR = ccoModel.CardNumber.Substring(0, 6);
                }
                /*Bin Str*/

                if (!(ccoModel != null && ccoModel.CardNumber != null && ((CardType == "3" && ccoModel.CardNumber.Length == 15) || (CardType != "3" && ccoModel.CardNumber.Length == 16)) && cardNumber > 0 && cvv != null && ((CardType == "3" && cvv.ToString().Length == 4) || (CardType != "3" && cvv.ToString().Length == 3)) && ccoModel.ValidMonth > 0 && ccoModel.ValidYear > 0 && !String.IsNullOrEmpty(ccoModel.CardOwnerName)))
                {
                    dataOK = false;
                    ccoModel.Message4 = "<span class=\"checkOut-Error-Text\">Kart bilgilerini kontrol ediniz.</span>";
                }
                else if (ccoModel.SelectedInstallment > ccoModel.MaxInstallmentCount)
                {
                    dataOK = false;
                    ccoModel.Message4 = "<span class=\"checkOut-Error-Text\">Taksit sayısı izin verilenden yüksek olamaz.</span>";
                }


                if (ccoTempModel.IsTotalPayment == false)
                {
                    if (ccoModel.PartialPayment.HasValue && ccoModel.PartialPayment.Value > 0 && ccoModel.PartialPayment.Value <= ccoModel.TotalPayment)
                    {
                        Payment = ccoModel.PartialPayment.Value;
                        if (ccoModel.PartialPayment.Value == ccoModel.TotalPayment)
                        {
                            ccoModel.IsTotalPayment = true;
                            ccoModel.PartialPayment = null;
                        }
                    }
                    else
                    {
                        dataOK = false;
                        ccoModel.Message3 = "<span class=\"checkOut-Error-Text\">Parçalı ödeme tutarını kontrol ediniz. Girilmemiş yada toplam ödeme tutarından fazla olabilir.</span>";
                    }
                }
                else
                {
                    Payment = ccoModel.ContractTotalPrice;
                }

                PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();

                PaymentUtils oPos = new PaymentUtils();

                Pos aPos = new Pos();
                if (ccoModel.SelectedInstallment < 2)
                {
                    #region Tek Çekim Default POS kullanımı

                    if (Parameters.UseSelfPosOneInstallment && ccoModel.BinList.Where(o => o.PosVoucher == "P").Select(o => o.Bin.ToString()).Contains(BinSTR))
                    {
                        var selectedPosByBin = ccoModel.BinList.Where(o => o.PosVoucher == "P" && o.Bin.ToString() == BinSTR).FirstOrDefault().PosId;
                        aPos = PosProcess.GetPos(selectedPosByBin); // dbPos.Get(Parameters.DefaultPosId);
                        if (aPos == null)
                        {
                            Logger.Write("Seçilen POS bulunamadı BIN listesinde eksik olabilir = " + selectedPosByBin.ToString() + " BIN: " + BinSTR + ". Seçilen POS ile işleme devam ediliyor", "Exception");
                            aPos = PosProcess.GetPos(ccoModel.SelectedPos); // dbPos.Get(ccoModel.SelectedPos);
                        }
                    }
                    else if (Parameters.DefaultPosId > 0)
                    {
                        aPos = PosProcess.GetPos(Parameters.DefaultPosId); // dbPos.Get(Parameters.DefaultPosId);
                        if (aPos == null)
                        {
                            Logger.Write("Varsayılan POS bulunamadı 2016 nolu referans = " + Parameters.DefaultPosId.ToString() + ". Seçilen POS ile işleme devam ediliyor", "Exception");
                            aPos = PosProcess.GetPos(ccoModel.SelectedPos); // dbPos.Get(ccoModel.SelectedPos);
                        }
                    }
                    #endregion
                }
                else
                {
                    aPos = PosProcess.GetPos(ccoModel.SelectedPos); // dbPos.Get(ccoModel.SelectedPos);
                }

                if (!ccoModel.Use3D && Parameters.Use3DPayment && aPos.Enabled3D && ccoModel.ContractTotalPrice > Parameters.Force3DPaymentPriceMinLimit)
                {
                    dataOK = false;
                    ccoModel.Message4 = "<span class=\"checkOut-Error-Text\">Toplam Tutar Kontrol Limiti Üzerinde, 3D Ödeme Seçimi Yapınız.</span>";
                }

                #endregion

                if (dataOK)
                {
                    #region Ziyaretçi ise kaydol.

                    if (eStoreUser.AccountType == 1 && !ccoModel.VisitorRegistered)
                    {
                        CreateAccountForPayment(ccoModel);
                        ccoModel.VisitorRegistered = true;
                    }
                    #endregion

                    #region POS

                    // Test için Start
                    //POSResult posResult = new POSResult();
                    //posResult.ApproveCode = aPos.ApproveCode;
                    //posResult.OrderID = "ORID1234546356456546";
                    // Test için End



                    if (ccoModel.Use3D)
                    {
                        #region Start 3D Validation

                        Session["OMAY_Payment_CCNo"] = ccoModel.CardNumber;
                        Session["OMAY_Payment_Month"] = ccoModel.ValidMonth;
                        Session["OMAY_Payment_Year"] = ccoModel.ValidYear;
                        Session["OMAY_Payment_CVV"] = cvv;
                        Session["OMAY_Payment_CardOwner"] = ccoModel.CardOwnerName;
                        string sessionId = Guid.NewGuid().ToString("N");
                        Session["OMAY_Payment_SessionId"] = sessionId;

                        Response.Clear();
                        string strTimeStamp = Parameters.Now.ToString("yyyyMMddHHmmss");
                        string strOrderID = Guid.NewGuid().ToString("N"); //"ORID" + eStoreUser.AccountId.ToString("000000") + strTimeStamp;

                        dbPayment.Insert(sessionId, eStoreUser.AccountId, Parameters.Now, "QUE", 1, pi.TotalInterestPrice, pi.TotalInterestPrice, aPos.PosId, (short)ccoModel.SelectedInstallment, ccoModel.SelectedCargoCompanyId, ccoModel.CargoAddressId, ccoModel.InvoiceAddressId, strOrderID, Utils.UserIP, "");

                        string formHtml = oPos.Start3D(aPos, eStoreUser.Email, sessionId, strTimeStamp, strOrderID, ccoModel.SelectedInstallment.ToString(), eStoreUser.AccountId, ccoModel.CardNumber, ccoModel.ValidMonth, ccoModel.ValidYear, cvv, ccoModel.CardOwnerName, pi.TotalInterestPrice, ccoModel.InvoiceAddress);

                        Logger.Write("Sent Form : " + formHtml, "Trace");

                        return Content(formHtml);

                        #endregion
                    }

                    POSResult posResult = oPos.Send(aPos, eStoreUser.Email, ccoModel.SelectedInstallment.ToString(), eStoreUser.AccountId, ccoModel.CardNumber, ccoModel.ValidMonth, ccoModel.ValidYear, cvv, ccoModel.CardOwnerName, pi.TotalInterestPrice, false, "", "", ccoModel.InvoiceAddress);

                    VoucherComment = VoucherComment + posResult.OrderID ?? "";

                    #region Log XML

                    try
                    {
                        Logger.Write(aPos.BankName + " -> " + posResult.RequestXMLString.Replace(ccoModel.CardNumber, ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4)), "Trace");
                    }
                    catch
                    { }

                    try
                    {
                        Logger.Write(aPos.BankName + " -> " + posResult.ResponseXMLString.Replace(ccoModel.CardNumber, ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4)), "Trace");
                    }
                    catch
                    { }

                    #endregion

                    #endregion

                    if (posResult.ApproveCode == aPos.ApproveCode)
                    {
                        #region Success - Credit Card Checkout

                        PaymentSucceeded = true;

                        PaymentId = dbVoucher.Insert(eStoreUser.AccountId, (short)PaymentTypes.KrediKart.GetHashCode(), true, false, 0, Parameters.Now.AddYears(10), eStoreUser.AccountId, pi.TotalInterestPrice, true, VoucherComment, false, ccoModel.CardOwnerName + " - " + ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4), aPos.PosId, (short)ccoModel.SelectedInstallment, aPos.BankId, Parameters.Now);

                        //if (ccoModel.SelectedInstallment <= 1) HavaleEFTIndirimi = Parameters.CreditCardDiscount - 1;
                        //else HavaleEFTIndirimi = (1 - pi.CommissionRate) * 100; // - değer olacak

                        KomisyonOrani = pi.CommissionRate;
                        KampanyaKomisyonOrani = pi.CampaignCommissionRate;

                        if (ccoModel.SelectedInstallment > 1)
                        {
                            KrediKartIndirimi = Parameters.CreditCardDiscount;
                        }

                        #endregion
                    }
                    else
                    {
                        #region Error - Credit Card Checkout

                        ccoModel.Message4 = "<span class=\"checkOut-Error-Text\">" + posResult.Explanation + " - " + posResult.Message + "</span>";

                        #endregion
                    }
                }

                #endregion
            }
            else if (ccoTempModel.SelectedAction == "120" || ccoTempModel.SelectedAction == "HavaleEft")
            {
                ccoTempModel.SelectedAction = "120";
                OrderPaymentType = "H";

                #region Payment Type - Money Transfer

                #region Is Data OK

                int HavaleHariciOdemeSayisi = ccoModel.VoucherList.Where(v => v.Selected == true && v.TypeId > 100 && v.TypeId != 120).Count();
                if (HavaleHariciOdemeSayisi == 0 && Parameters.UseTransferDiscount)
                {
                    ccoModel.TotalPayment = ccoModel.TotalPaymentWithTransfer;
                    HavaleEFTIndirimi = Parameters.TransferDiscount;
                }

                if (ccoModel.SelectedBank <= 0)
                {
                    dataOK = false;
                    ccoModel.Message4 = "<span class=\"checkOut-Error-Text\">Banka seçimi yapmadınız. Ödemeyi yapacağınız bankayı seçiniz.</span>";
                }

                if (ccoTempModel.IsTotalPayment == false)
                {
                    if (ccoModel.PartialPayment.HasValue && ccoModel.PartialPayment.Value > 0 && ccoModel.PartialPayment.Value <= ccoModel.TotalPayment)
                    {
                        Payment = ccoModel.PartialPayment.Value;
                        if (ccoModel.PartialPayment.Value == ccoModel.TotalPayment)
                        {
                            ccoModel.IsTotalPayment = true;
                            ccoModel.PartialPayment = null;
                        }
                    }
                    else
                    {
                        dataOK = false;
                        ccoModel.Message3 = "<span class=\"checkOut-Error-Text\">Parçalı ödeme tutarını kontrol ediniz. Girilmemiş yada toplam ödeme tutarından fazla olabilir.</span>";
                    }
                }
                else
                {
                    Payment = ccoModel.TotalPaymentWithTransfer > 0 ? ccoModel.TotalPaymentWithTransfer : ccoModel.TotalPayment;
                }

                #endregion

                if (dataOK)
                {
                    #region Ziyaretçi ise kaydol.

                    if (eStoreUser.AccountType == 1 && !ccoModel.VisitorRegistered)
                    {
                        CreateAccountForPayment(ccoModel);
                        ccoModel.VisitorRegistered = true;
                    }
                    #endregion

                    #region Money Transfer DB Insert

                    PaymentId = dbVoucher.Insert(eStoreUser.AccountId, (short)PaymentTypes.HavaleEft.GetHashCode(), true, false, 0, Parameters.Now.AddYears(10), eStoreUser.AccountId, Payment, false, "", false, "", 0, 0, ccoModel.SelectedBank, Parameters.Now);

                    #endregion

                    if (PaymentId > 0)
                    {
                        #region Success - Money Transfer

                        PaymentSucceeded = true;

                        #endregion
                    }
                    else
                    {
                        #region Error - Money Transfer

                        ccoModel.Message5 = "<span class=\"checkOut-Error-Text\">" + "Beklenmeyen bir hata oluştu, daha sonra tekrar deneyin" + "</span>";

                        #endregion
                    }
                }

                #endregion
            }
            else if (ccoTempModel.SelectedAction == "160" || ccoTempModel.SelectedAction == "KapidaOdeme")
            {
                ccoTempModel.SelectedAction = "160";
                OrderPaymentType = "M";

                #region Payment Type - Kapıda Ödeme

                #region Temp to ccoModel

                //ccoModel.PartialPayment = ccoTempModel.PartialPayment;
                //ccoModel.PaymentType = ccoTempModel.PaymentType;

                #endregion

                #region Is Data OK

                if (ccoTempModel.IsTotalPayment == false)
                {
                    if (ccoModel.PartialPayment.HasValue && ccoModel.PartialPayment.Value > 0 && ccoModel.PartialPayment.Value <= ccoModel.TotalPayment)
                    {
                        Payment = ccoModel.PartialPayment.Value;
                        if (ccoModel.PartialPayment.Value == ccoModel.TotalPayment)
                        {
                            ccoModel.IsTotalPayment = true;
                            ccoModel.PartialPayment = null;
                        }
                    }
                    else
                    {
                        dataOK = false;
                        ccoModel.Message3 = "<span class=\"checkOut-Error-Text\">Parçalı ödeme tutarını kontrol ediniz. Girilmemiş yada toplam ödeme tutarından fazla olabilir.</span>";
                    }
                }
                else
                {
                    if (ccoModel.TotalPaymentWithCreditCard > 0)
                    {
                        Payment = ccoModel.TotalPaymentWithCreditCard;
                    }
                    else
                    {
                        Payment = ccoModel.TotalPayment;
                    }
                }

                #endregion

                if (dataOK)
                {
                    #region Ziyaretçi ise kaydol.

                    if (eStoreUser.AccountType == 1 && !ccoModel.VisitorRegistered)
                    {
                        CreateAccountForPayment(ccoModel);
                        ccoModel.VisitorRegistered = true;
                    }
                    #endregion

                    #region Kapıda Ödeme DB Insert

                    PaymentId = dbVoucher.Insert(eStoreUser.AccountId, (short)PaymentTypes.KapidaOdeme.GetHashCode(), true, false, 0, Parameters.Now.AddYears(10), eStoreUser.AccountId, Payment, false, "", false, "", 0, 0, 0, Parameters.Now);

                    #endregion

                    if (PaymentId > 0)
                    {
                        #region Success - Money Transfer

                        PaymentSucceeded = true;

                        #endregion
                    }
                    else
                    {
                        #region Error - Money Transfer

                        ccoModel.Message5 = "<span class=\"checkOut-Error-Text\">" + "Beklenmeyen bir hata oluştu, daha sonra tekrar deneyin" + "</span>";

                        #endregion
                    }
                }

                #endregion
            }
            else if (ccoTempModel.SelectedAction == "170" || ccoTempModel.SelectedAction == "AnindaKrediOdeme")
            {
                ccoTempModel.SelectedAction = "170";
                OrderPaymentType = "AK";

                #region Payment Type - Anında Kredi ile Ödeme

                if (string.IsNullOrEmpty(ccoModel.SelectedInstallment.ToString()) || string.IsNullOrEmpty(ccoModel.OtherNameSurname) || string.IsNullOrEmpty(ccoModel.OtherTcKimlikNo) || string.IsNullOrEmpty(ccoModel.OtherMonthlyIncoming) || string.IsNullOrEmpty(ccoModel.OtherFatherName) || string.IsNullOrEmpty(ccoModel.OtherMotherName))
                {
                    ccoModel.Message11 = "<span class=\"checkOut-Error-Text\">" + "Lütfen Gerekli Alanları Doldurun." + "</span>";
                    dataOK = false;
                }
                else
                {
                    #region krediBilgileri
                    if (!string.IsNullOrEmpty(ccoModel.SelectedInstallment.ToString()))
                    {
                        OrderComment += " Taksit Sayısı: (" + ccoModel.SelectedInstallment.ToString() + ")\n";
                        VoucherComment += " Taksit Sayısı: (" + ccoModel.SelectedInstallment.ToString() + ")\n";
                    }
                    if (!string.IsNullOrEmpty(ccoModel.OtherNameSurname))
                    {
                        OrderComment += " İsim Soyisim: (" + ccoModel.OtherNameSurname + ")\n";
                        VoucherComment += " İsim Soyisim: (" + ccoModel.OtherNameSurname + ")\n";
                    }
                    if (!string.IsNullOrEmpty(ccoModel.OtherTcKimlikNo))
                    {
                        OrderComment += " TC Kimlik No: (" + ccoModel.OtherTcKimlikNo + ")\n";
                        VoucherComment += " TC Kimlik No: (" + ccoModel.OtherTcKimlikNo + ")\n";
                    }
                    if (!string.IsNullOrEmpty(ccoModel.OtherMonthlyIncoming))
                    {
                        OrderComment += " Aylık Gelir: (" + ccoModel.OtherMonthlyIncoming + ")\n";
                        VoucherComment += " Aylık Gelir: (" + ccoModel.OtherMonthlyIncoming + ")\n";
                    }
                    if (!string.IsNullOrEmpty(ccoModel.OtherFatherName))
                    {
                        OrderComment += " Baba Adı: (" + ccoModel.OtherFatherName + ")\n";
                        VoucherComment += " Baba Adı: (" + ccoModel.OtherFatherName + ")\n";
                    }
                    if (!string.IsNullOrEmpty(ccoModel.OtherMotherName))
                    {
                        OrderComment += " Anne Adı: (" + ccoModel.OtherMotherName + ")\n";
                        VoucherComment += " Anne Adı: (" + ccoModel.OtherMotherName + ")\n";
                    }
                    #endregion

                    #region Temp to ccoModel

                    //ccoModel.PartialPayment = ccoTempModel.PartialPayment;
                    //ccoModel.PaymentType = ccoTempModel.PaymentType;

                    #endregion

                    #region Is Data OK

                    if (ccoTempModel.IsTotalPayment == false)
                    {
                        if (ccoModel.PartialPayment.HasValue && ccoModel.PartialPayment.Value > 0 && ccoModel.PartialPayment.Value <= ccoModel.TotalPayment)
                        {
                            Payment = ccoModel.PartialPayment.Value;
                            if (ccoModel.PartialPayment.Value == ccoModel.TotalPayment)
                            {
                                ccoModel.IsTotalPayment = true;
                                ccoModel.PartialPayment = null;
                            }
                        }
                        else
                        {
                            dataOK = false;
                            ccoModel.Message3 = "<span class=\"checkOut-Error-Text\">Parçalı ödeme tutarını kontrol ediniz. Girilmemiş yada toplam ödeme tutarından fazla olabilir.</span>";
                        }
                    }
                    else
                    {

                        PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                        Payment = pi.TotalInterestPrice;
                        KomisyonOrani = pi.CommissionRate;
                        KampanyaKomisyonOrani = pi.CampaignCommissionRate;
                    }

                    #endregion

                    if (dataOK)
                    {
                        #region Ziyaretçi ise kaydol.

                        if (eStoreUser.AccountType == 1 && !ccoModel.VisitorRegistered)
                        {
                            CreateAccountForPayment(ccoModel);
                            ccoModel.VisitorRegistered = true;
                        }
                        #endregion

                        #region Anında Kredi ile Ödeme DB Insert

                        PaymentId = dbVoucher.Insert(eStoreUser.AccountId, (short)PaymentTypes.AnindaKrediOdeme.GetHashCode(), true, false, 0, Parameters.Now.AddYears(10), eStoreUser.AccountId, Payment, false, "", false, "", 0, 0, 0, Parameters.Now);

                        #endregion

                        if (PaymentId > 0)
                        {
                            #region Success - Money Transfer

                            PaymentSucceeded = true;

                            #endregion
                        }
                        else
                        {
                            #region Error - Money Transfer

                            ccoModel.Message5 = "<span class=\"checkOut-Error-Text\">" + "Beklenmeyen bir hata oluştu, daha sonra tekrar deneyin" + "</span>";

                            #endregion
                        }
                    }

                }

                #endregion
            }

            else if (ccoTempModel.SelectedAction == "180" || ccoTempModel.SelectedAction == "SenetleOdeme")
            {
                ccoTempModel.SelectedAction = "180";
                OrderPaymentType = "S";

                #region Payment Type - Senetle Ödeme

                if (string.IsNullOrEmpty(ccoModel.Kimlik.FirstName) || string.IsNullOrEmpty(ccoModel.Kimlik.LastName) || string.IsNullOrEmpty(ccoModel.Kimlik.Baba_Ad) || string.IsNullOrEmpty(ccoModel.Kimlik.Anne_Ad)
                     || string.IsNullOrEmpty(ccoModel.Kimlik.N_TCKimlikNo) || string.IsNullOrEmpty(ccoModel.Kimlik.Cinsiyet) || string.IsNullOrEmpty(ccoModel.Kimlik.DogumYer) || string.IsNullOrEmpty(ccoModel.Kimlik.BirthDayNumber)
                     || string.IsNullOrEmpty(ccoModel.Kimlik.BirthMonth) || string.IsNullOrEmpty(ccoModel.Kimlik.BirthYear) || string.IsNullOrEmpty(ccoModel.Kimlik.EvAdres) || string.IsNullOrEmpty(ccoModel.Kimlik.EvTel)
                     || string.IsNullOrEmpty(ccoModel.Kimlik.CepTel) || string.IsNullOrEmpty(ccoModel.Kimlik.IsYeriAdi) || string.IsNullOrEmpty(ccoModel.Kimlik.IsAdres) || string.IsNullOrEmpty(ccoModel.Kimlik.IsTel)
                     || string.IsNullOrEmpty(ccoModel.Kimlik.IsGorev) || string.IsNullOrEmpty(ccoModel.Kimlik.N_SeriNo) || string.IsNullOrEmpty(ccoModel.Kimlik.N_Cuzdan_No) || string.IsNullOrEmpty(ccoModel.Kimlik.N_Cuzdan_No)
                     || string.IsNullOrEmpty(ccoModel.Kimlik.N_CiltNo) || string.IsNullOrEmpty(ccoModel.Kimlik.N_AileSiraNo) || string.IsNullOrEmpty(ccoModel.Kimlik.N_KutukIl) || string.IsNullOrEmpty(ccoModel.Kimlik.N_Ilce)
                     || string.IsNullOrEmpty(ccoModel.Kimlik.N_Mahalle) || string.IsNullOrEmpty(ccoModel.Kimlik.AylikGelir))
                {
                    ccoModel.Message11 = "<span class=\"checkOut-Error-Text\">" + "Lütfen Gerekli Alanları Doldurun." + "</span>";
                    dataOK = false;
                }
                else if (ccoModel.VoucherAvailable == 1 && !TCKimlikMod(ccoModel.Kimlik.N_TCKimlikNo))
                {
                    dataOK = false;
                    ccoModel.Message1 = "<span class=\"checkOut-Error-Text\">Eksik veya hatalı bir TC Kimlik numarası girdiniz.</span>";
                }
                else if (ccoModel.SelectedInstallment <= 0)
                {
                    dataOK = false;
                    ccoModel.Message1 = "<span class=\"checkOut-Error-Text\">Taksit seçimi yapmadınız. Devam etmeden önce taksit seçiniz.</span>";
                }
                else
                {
                    #region Temp to ccoModel

                    //ccoModel.PartialPayment = ccoTempModel.PartialPayment;
                    //ccoModel.PaymentType = ccoTempModel.PaymentType;

                    #endregion

                    #region Is Data OK

                    PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                    Payment = pi.TotalInterestPrice;
                    KomisyonOrani = pi.CommissionRate;
                    KampanyaKomisyonOrani = pi.CampaignCommissionRate;
                    #endregion

                    if (dataOK)
                    {

                        #region Ziyaretçi ise kaydol.

                        if (eStoreUser.AccountType == 1 && !ccoModel.VisitorRegistered)
                        {
                            CreateAccountForPayment(ccoModel);
                            ccoModel.Guarantor1Id = eStoreUser.SelectedGuarantor1Id;
                            ccoModel.Guarantor2Id = eStoreUser.SelectedGuarantor2Id;
                            ccoModel.VisitorRegistered = true;
                        }
                        #endregion

                        #region Senetle Ödeme DB Insert

                        PaymentId = dbVoucher.Insert(eStoreUser.AccountId, (short)PaymentTypes.SenetleOdeme.GetHashCode(), true, false, 0, Parameters.Now.AddYears(10), eStoreUser.AccountId, Payment, false, "", false, "", ccoModel.SelectedPos, (short)ccoModel.SelectedInstallment, ccoModel.SelectedPos, Parameters.Now);

                        #endregion

                        if (PaymentId > 0)
                        {
                            #region Identity and Guarantors

                            int indentityResult = 0;
                            int guarantor1Result = 0;
                            int guarantor2Result = 0;

                            ccoModel.Kimlik.BirthDayNumber = Convert.ToInt32(ccoModel.Kimlik.BirthDayNumber) < 10 ? "0" + ccoModel.Kimlik.BirthDayNumber : ccoModel.Kimlik.BirthDayNumber;
                            ccoModel.Kimlik.BirthMonth = Convert.ToInt32(ccoModel.Kimlik.BirthMonth) < 10 ? "0" + ccoModel.Kimlik.BirthMonth : ccoModel.Kimlik.BirthMonth;
                            string Kdate = ccoModel.Kimlik.BirthYear + "-" + ccoModel.Kimlik.BirthMonth + "-" + ccoModel.Kimlik.BirthDayNumber;
                            string Ktime = "00:00:00";
                            ccoModel.Kimlik.DogumTarihi = DateTime.ParseExact(Kdate + " " + Ktime, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                            indentityResult = dbAccount.SetOrderUserIdentity((int)PaymentId, eStoreUser.AccountId, ccoModel.Kimlik);
                            if (ccoModel.Guarantor1Id > 0)
                            {
                                guarantor1Result = dbAccount.SetOrderUserGuarantor((int)PaymentId, eStoreUser.AccountId, ccoModel.Guarantor1Id);
                            }
                            if (ccoModel.Guarantor2Id > 0)
                            {
                                guarantor2Result = dbAccount.SetOrderUserGuarantor((int)PaymentId, eStoreUser.AccountId, ccoModel.Guarantor2Id);
                            }


                            #endregion


                            #region Success - Money Transfer

                            PaymentSucceeded = true;

                            #endregion
                        }
                        else
                        {
                            #region Error - Money Transfer

                            ccoModel.Message5 = "<span class=\"checkOut-Error-Text\">Beklenmeyen bir hata oluştu, daha sonra tekrar deneyin</span>";

                            #endregion
                        }
                    }
                }

                #endregion
            }

            #region PaymentSucceeded

            if (PaymentSucceeded)
            {
                if (Parameters.UsePartialPayment && Payment < ccoModel.ContractTotalPrice)
                {
                    #region Parçalı Ödeme

                    ccoModel = Get_ccoModel(ccoTempModel);
                    ccoModel.PartialPayment = null;
                    ccoModel.IsTotalPayment = true;
                    ccoModel.PaymentType = PaymentTypes.KrediKart;

                    ViewData.ModelState.Clear();

                    #endregion
                }
                else
                {
                    #region Tüm Ödeme Tamamlandı

                    ccoModel.ContractText = CreateContractText(ccoModel.CargoAddressId, ccoModel.InvoiceAddressId, ccoModel.PaymentType.ToString(), ccoModel.CargoTotalPrice, ccoModel.ContractTotalPrice, ccoModel.SelectedPos);

                    Summary cartSummary = new Summary();

                    cartSummary.TotalQty = eStoreUser.TotalQty;
                    cartSummary.TotalPrice = eStoreUser.TotalPrice;
                    cartSummary.InstallmentPrice = eStoreUser.InstallmentPrice;
                    cartSummary.InstallmentTax = eStoreUser.InstallmentTax;
                    cartSummary.TotalPriceCreditCard = Math.Round(eStoreUser.TotalPrice / Parameters.CreditCardDiscount, 2);

                    IList<Cart> Basket = dbCart.GetList(eStoreUser.AccountId, eStoreUser.AccountType);

                    string table = "";
                    string tableVoucher = "";
                    if (ccoTempModel.SelectedAction == "180" || ccoTempModel.SelectedAction == "SenetleOdeme")
                    {
                        tableVoucher = "<tbody>";
                        tableVoucher += "<tr>";
                        tableVoucher += "<td style=\"text-align: center; border: 1px solid #000000;\">Kod</td>";
                        tableVoucher += "<td style=\"text-align: center; border: 1px solid #000000; border-left: none !important;\">Malın Cinsi</td>";
                        tableVoucher += "<td style=\"text-align: center; border: 1px solid #000000; border-left: none !important;\">Adedi</td>";
                        tableVoucher += "<td style=\"text-align: center; border: 1px solid #000000; border-left: none !important;\">Birim Fiyatı</td>";
                        tableVoucher += "<td style=\"text-align: center; border: 1px solid #000000; border-left: none !important;\">Tutarı</td>";
                        tableVoucher += "</tr>";
                        foreach (var rows in Basket)
                        {
                            string StockPrice = "";
                            if (rows.Qty > 0)
                            {
                                StockPrice = (rows.Price * rows.Qty * ((rows.CampaignProduct && KampanyaKomisyonOrani > 0) ? KampanyaKomisyonOrani : KomisyonOrani)).ToString("###,###,##0.00");
                            }
                            else
                            {
                                StockPrice = (rows.Price * ((rows.CampaignProduct && KampanyaKomisyonOrani > 0) ? KampanyaKomisyonOrani : KomisyonOrani)).ToString("###,###,##0.00");
                            }
                            StockPrice += " " + rows.Currency;

                            tableVoucher += "<tr>";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000; border-left: 1px solid #000000;\">" + rows.ProductId + "</td> ";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000;\"><a href=\"" + Parameters.WebSiteUrl + "/" + rows.LinkUrl + "\" target=\"_blank\">" + rows.ProductName + (!string.IsNullOrEmpty(rows.Model) ? " - " + rows.Model : "") + "</a></td>";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + rows.Qty.ToString("###,###.###") + " Adet</td>";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + (rows.Price * ((rows.CampaignProduct && KampanyaKomisyonOrani > 0) ? KampanyaKomisyonOrani : KomisyonOrani)).ToString("###,###,##0.00") + " " + rows.Currency + "</td>";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + StockPrice + "</td>";
                            tableVoucher += " </tr>";
                        }
                        if (ccoModel.CargoPrice > 0)
                        {

                            tableVoucher += "<tr>";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000; border-left: 1px solid #000000;\">" + ccoModel.CargoList.Where(o => o.CargoId == ccoModel.SelectedCargoCompanyId).FirstOrDefault().ProductId.ToString() + "</td> ";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000;\">Kargo Bedeli</td>";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000;\">1 Adet</td>";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + (ccoModel.CargoPrice * KomisyonOrani).ToString("###,###,##0.00") + " TL</td>";
                            tableVoucher += "<td style=\"text-align: center; border-right: 1px solid #000000;\">" + (ccoModel.CargoPrice * KomisyonOrani).ToString("###,###,##0.00") + " TL</td>";
                            tableVoucher += " </tr>";
                        }
                        tableVoucher += "<tr>";
                        tableVoucher += "<td style=\"text-align:right; border-top: 1px solid #000000; border-right: 1px solid #000000; border-left: 1px solid #000000;\" colspan=\"4\"><b>Toplam<&nbsp;</b></td>";
                        tableVoucher += "<td style=\"text-align: center; border-top: 1px solid #000000; border-right: 1px solid #000000;\"><b>" + ((cartSummary.TotalPrice + ccoModel.CargoPrice) * KomisyonOrani).ToString("###,###,##0.00") + " TL</b></td>";
                        tableVoucher += "</tr>";
                        tableVoucher += "<tr>";
                        tableVoucher += "<td style=\"text-align:right; border-top: 1px solid #000000; border-right: 1px solid #000000; border-left: 1px solid #000000;\" colspan=\"4\"><b>Taksit Sayısı&nbsp;</b></td>";
                        tableVoucher += "<td style=\"text-align: center; border-top: 1px solid #000000; border-right: 1px solid #000000;\"><b>{InstallmentCount}</b></td>";
                        tableVoucher += "</tr>";
                        tableVoucher += "</tbody>";

                    }

                    table = "<table width=\"750\" style=\"border: 1px solid #bababa; margin:0; padding:0;\">";
                    table += "<tr>";
                    table += "<td style=\"border-right: 1px solid #bababa; margin:0; padding:5px; width:350px;font: normal 14px Arial, Tahoma;\"><b>Stok No</b></td>";
                    table += "<td style=\"border-right: 1px solid #bababa; margin:0; padding:5px; width:350px;font: normal 14px Arial, Tahoma;\" colspan=\"2\"><b>Ürün</b></td>";
                    table += "<td style=\"border-right: 1px solid #bababa; margin:0; padding:5px; width:350px;font: normal 14px Arial, Tahoma;\"><b>Adet</b></td>";
                    table += "<td style=\"margin:0; padding:5px; width:350px;font: normal 14px Arial, Tahoma;\"><b>Tutar</b></td>";
                    table += "</tr>";

                    foreach (var rows in Basket)
                    {
                        string StockPrice = "";
                        if (rows.Qty > 0)
                        {
                            StockPrice = (rows.Price * rows.Qty).ToString("###,###,##0.00");
                        }
                        else
                        {
                            StockPrice = rows.Price.ToString("###,###,##0.00");
                        }
                        StockPrice += " " + rows.Currency;

                        table += "<tr style=\"margin:0; padding:0;\">";
                        table += "<td style=\"border-right: 1px solid #bababa; border-top: 1px solid #bababa; margin:0; padding:5px;font: normal 14px Arial, Tahoma;\" width=\"25\"> " + rows.ProductId + "</td>";
                        table += "<td style=\"border-right: 1px solid #ffffff; border-top: 1px solid #bababa;margin:0; padding:5px; text-align:center;\" height=\"75\"><a href=\"" + Parameters.WebSiteUrl + "/" + rows.LinkUrl + "\" target=\"_blank\"><img src=\"" + Parameters.WebSiteImageUrl + "/product-medium/" + rows.ProductId + "_1.jpg\" width=\"75\" style=\"margin-right:10px;\"></a></td>";
                        table += "<td style=\"border-right: 1px solid #bababa; border-top: 1px solid #bababa;margin:0; padding:5px; font: normal 14px Arial, Tahoma;\" width=\"450\"><a href=\"" + Parameters.WebSiteUrl + "/" + rows.LinkUrl + "\" target=\"_blank\">" + rows.ProductName + (!string.IsNullOrEmpty(rows.Model) ? " - " + rows.Model : "") + "</a></td>";
                        table += "<td style=\"border-right: 1px solid #bababa; border-top: 1px solid #bababa; margin:0; padding:5px;font: normal 14px Arial, Tahoma;\" width=\"60\">" + rows.Qty.ToString("###,###.###") + " " + rows.Birim + "</td>";
                        table += "<td style=\"border-right: none;  border-top: 1px solid #bababa;margin:0; padding:5px;font: normal 14px Arial, Tahoma;\" width=\"65\">" + StockPrice + "</td>";
                        table += "</tr>";
                    }
                    table += "<tr>";
                    table += "<td style=\"border-right: 1px solid #bababa; border-top: 1px solid #bababa; margin:0; padding:5px; width:350px;font: normal 14px Arial, Tahoma; text-align:right;\" colspan=\"4\"><b>Toplam&nbsp;</b></td>";
                    table += "<td style=\"border-top: 1px solid #bababa; margin:0; padding:5px; width:350px;font: normal 14px Arial, Tahoma;\"><b>" + cartSummary.TotalPriceCreditCard.ToString("###,###,##0.00") + " TL</b></td>";
                    table += "</tr>";
                    if (ccoTempModel.SelectedAction == "180" || ccoTempModel.SelectedAction == "SenetleOdeme")
                    {
                        table += "<tr>";
                        table += "<td style=\"border-right: 1px solid #bababa; border-top: 1px solid #bababa; margin:0; padding:5px; width:350px;font: normal 14px Arial, Tahoma; text-align:right;\" colspan=\"4\"><b>Taksit Sayısı: &nbsp;</b></td>";
                        table += "<td style=\"border-top: 1px solid #bababa; margin:0; padding:5px; width:350px;font: normal 14px Arial, Tahoma;\"><b>{InstallmentCount}</b></td>";
                        table += "</tr>";
                    }
                    table += "</table>";

                    int orderId = dbCart.CreateOrder(eStoreUser.AccountId, 0, OrderPaymentType, Parameters.Now, ccoModel.CargoWithInvoice, eStoreUser.AccountId, KomisyonOrani, KampanyaKomisyonOrani, KrediKartIndirimi, HavaleEFTIndirimi, ccoModel.SelectedCargoCompanyId, ccoModel.CargoPrice, ccoModel.CargoPrice2, ccoModel.TransportPrice, ccoModel.TransportAvailable, ccoModel.InstallationPrice, ccoModel.InstallationAvailable, ccoModel.CargoAddress.City, OrderComment);

                    #region Selected Vouchers and Payments + Last Payment set as Used

                    foreach (Voucher voucher in ccoModel.VoucherList)
                    {
                        if (voucher.Selected)
                        {
                            dbVoucher.Update(eStoreUser.AccountId, voucher.VoucherId, false, true, eStoreUser.AccountId, orderId, false, "");
                        }
                    }

                    dbVoucher.Update(eStoreUser.AccountId, PaymentId, false, true, eStoreUser.AccountId, orderId, false, VoucherComment);

                    #endregion

                    #region Order Addresses Create

                    if (ccoModel.CargoAddressId > 0)
                    {
                        dbAddressOrder.Insert(111, orderId, "CAR", string.IsNullOrEmpty(ccoModel.CargoAddress.Name) ? ccoModel.UserName : ccoModel.CargoAddress.Name, "", "",
                                      Convert2.ToString(ccoModel.CargoAddress.Address1), Convert2.ToString(ccoModel.CargoAddress.Address2),
                                      Convert2.ToString(ccoModel.CargoAddress.County), Convert2.ToString(ccoModel.CargoAddress.PostalCode),
                                      ccoModel.CargoAddress.Country, ccoModel.CargoAddress.City, eStoreUser.AccountId, Convert2.ToString(ccoModel.CargoAddress.Phone));
                    }

                    if (ccoModel.InvoiceAddressId > 0)
                    {
                        dbAddressOrder.Insert(111, orderId, "INV", string.IsNullOrEmpty(ccoModel.InvoiceAddress.Name) ? ccoModel.UserName : ccoModel.InvoiceAddress.Name,
                                              Convert2.ToString(ccoModel.InvoiceAddress.TaxOffice), Convert2.ToString(ccoModel.InvoiceAddress.TaxNo),
                                              Convert2.ToString(ccoModel.InvoiceAddress.Address1), Convert2.ToString(ccoModel.InvoiceAddress.Address2),
                                              Convert2.ToString(ccoModel.InvoiceAddress.County), Convert2.ToString(ccoModel.InvoiceAddress.PostalCode),
                                              ccoModel.InvoiceAddress.Country, ccoModel.InvoiceAddress.City, eStoreUser.AccountId, Convert2.ToString(ccoModel.InvoiceAddress.Phone));
                    }

                    #endregion

                    #region Payment Succeeded Page

                    RefreshCartSummary();

                    string MessageBody = "";

                    if (ccoTempModel.SelectedAction == "110" || ccoTempModel.SelectedAction == "KrediKart")
                    {
                        MessageBody = dbRefs.GetRef5(122);
                        MessageBody = MessageBody.Replace("{FirstName}", eStoreUser.FirstName).Replace("{LastName}", eStoreUser.LastName).Replace("{ProductsTable}", table);
                    }
                    else if (ccoTempModel.SelectedAction == "120" || ccoTempModel.SelectedAction == "HavaleEft")
                    {
                        MessageBody = dbRefs.GetRef5(120);
                        MessageBody = MessageBody.Replace("{FirstName}", eStoreUser.FirstName).Replace("{LastName}", eStoreUser.LastName).Replace("{ProductsTable}", table);
                    }
                    else if (ccoTempModel.SelectedAction == "160" || ccoTempModel.SelectedAction == "KapidaOdeme")
                    {
                        MessageBody = dbRefs.GetRef5(121);
                        MessageBody = MessageBody.Replace("{FirstName}", eStoreUser.FirstName).Replace("{LastName}", eStoreUser.LastName).Replace("{ProductsTable}", table);
                    }
                    else if (ccoTempModel.SelectedAction == "170" || ccoTempModel.SelectedAction == "AnindaKrediOdeme")
                    {
                        MessageBody = dbRefs.GetRef5(126);
                        MessageBody = MessageBody.Replace("{FirstName}", eStoreUser.FirstName).Replace("{LastName}", eStoreUser.LastName).Replace("{ProductsTable}", table);
                    }
                    else if (ccoTempModel.SelectedAction == "180" || ccoTempModel.SelectedAction == "SenetleOdeme")
                    {
                        MessageBody = dbRefs.GetRef5(124);
                        OrderCompletedVoucher VC = dbVoucher.GetByOrderId(eStoreUser.AccountId, orderId);
                        var InstallmentCount = VC.InstallmentNo;
                        var PaymentAmount = VC.PaymentAmount;
                        var VoucherDate = VC.CreateDate.Day.ToString() + "/" + VC.CreateDate.Month.ToString() + "/" + VC.CreateDate.Year.ToString();
                        OrderUserInfo UserInfo = dbAccount.GetOrderUserInfo((int)PaymentId);

                        #region MemberInfo Table
                        string MemberInfo1 = "";
                        MemberInfo1 += "<tr>";
                        MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 15%;\">Adı Soyadı</td>";
                        string DogumTarihiStr = UserInfo.Kimlik.DogumTarihi.Day.ToString() + "/" + UserInfo.Kimlik.DogumTarihi.Month.ToString() + "/" + UserInfo.Kimlik.DogumTarihi.Year.ToString();
                        MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 22%;\">" + UserInfo.Kimlik.FirstName + " " + UserInfo.Kimlik.LastName + "<br />T.C. :" + UserInfo.Kimlik.N_TCKimlikNo + " - " + DogumTarihiStr + "</td>";
                        MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 10%; text-align: center;\" rowspan=\"3\">İş<br />Adresi</td>";
                        MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 20%; text-align: center;\" rowspan=\"3\">'Görevi: " + UserInfo.Kimlik.IsGorev + "' - " + UserInfo.Kimlik.IsYeriAdi + " - " + UserInfo.Kimlik.IsAdres + "</td>";
                        MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 10%;\">Ev Tel</td>";
                        MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 20%; border-right: 1px solid #000000;\">" + UserInfo.Kimlik.EvTel + "</td>";
                        MemberInfo1 += "</tr>";
                        MemberInfo1 += "<tr>";
                        MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000;\">Ev Adresi</td>";
                        MemberInfo1 += "<td style=\"border-left: 1px solid #000000;\">" + UserInfo.Kimlik.EvAdres + "</td>";
                        MemberInfo1 += "<td style=\"border-left: 1px solid #000000;\">Gsm</td>";
                        MemberInfo1 += "<td style=\"border-left: 1px solid #000000; border-right: 1px solid #000000;\">" + UserInfo.Kimlik.CepTel + "</td>";
                        MemberInfo1 += "</tr>";
                        MemberInfo1 += "<tr>";
                        var evkira = (UserInfo.Kimlik.EvKira) ? "Kendi Evi" : "Kiracı";
                        MemberInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000;\">Ev</td>";
                        MemberInfo1 += "<td style=\"border-left: 1px solid #000000;\">" + evkira + "</td>";
                        MemberInfo1 += "<td style=\"border-left: 1px solid #000000;\">İş Tel</td>";
                        MemberInfo1 += "<td style=\"border-left: 1px solid #000000; border-right: 1px solid #000000;\">" + UserInfo.Kimlik.IsTel + "</td>";
                        MemberInfo1 += "</tr>";
                        #endregion

                        #region Guarantors Table
                        string GuarantorInfo1 = "";
                        foreach (Guarantor Kefil in UserInfo.Kefiller)
                        {
                            GuarantorInfo1 += "<tr>";
                            GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 15%;\">Müşterek Müteselsil Kefilin Adı Soyadı</td>";
                            string KflDogumTarihiStr = Kefil.DogumTarihi.Day.ToString() + "/" + Kefil.DogumTarihi.Month.ToString() + "/" + Kefil.DogumTarihi.Year.ToString();
                            GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 22%;\">" + Kefil.FirstName + " " + Kefil.LastName + "<br />T.C. :" + Kefil.N_TCKimlikNo + " - " + KflDogumTarihiStr + "</td>";
                            GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 10%; text-align: center;\" rowspan=\"3\">İş<br />Adresi</td>";
                            GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 20%; text-align: center;\" rowspan=\"3\">'Görevi: " + Kefil.IsGorev + "' - " + Kefil.IsYeriAdi + " - " + Kefil.IsAdres + "</td>";
                            GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 10%;\">Ev Tel</td>";
                            GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000; width: 20%; border-right: 1px solid #000000;\">" + Kefil.EvTel + "</td>";
                            GuarantorInfo1 += "</tr>";
                            GuarantorInfo1 += "<tr>";
                            GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000;\">Ev Adresi</td>";
                            GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000;\">" + Kefil.EvAdres + "</td>";
                            GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000;\">Gsm</td>";
                            GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000; border-right: 1px solid #000000;\">" + Kefil.CepTel + "</td>";
                            GuarantorInfo1 += "</tr>";
                            GuarantorInfo1 += "<tr>";
                            var Kflevkira = (Kefil.EvKira) ? "Kendi Evi" : "Kiracı";
                            GuarantorInfo1 += "<td style=\"border-top: 1px solid #000000; border-left: 1px solid #000000;\">Ev</td>";
                            GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000;\">" + Kflevkira + "</td>";
                            GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000;\">İş Tel</td>";
                            GuarantorInfo1 += "<td style=\"border-left: 1px solid #000000; border-right: 1px solid #000000;\">" + Kefil.IsTel + "</td>";
                            GuarantorInfo1 += "</tr>";
                        }
                        #endregion

                        var Guarantor1FullName = "";
                        var Guarantor2FullName = "";
                        if (UserInfo.Kefiller.Count() > 0)
                        {
                            Guarantor1FullName = UserInfo.Kefiller.FirstOrDefault().FirstName + " " + UserInfo.Kefiller.FirstOrDefault().LastName;
                        }
                        if (UserInfo.Kefiller.Count() > 1)
                        {
                            Guarantor2FullName = UserInfo.Kefiller.Skip(1).FirstOrDefault().FirstName + " " + UserInfo.Kefiller.FirstOrDefault().LastName;
                        }

                        #region VoucherSection
                        var MemberInfo2 = "";
                        var GuarantorInfo2 = "";

                        MemberInfo2 = "<td>İsim:<br />Adres:</td>";
                        MemberInfo2 += "<td>" + UserInfo.Kimlik.FirstName + " " + UserInfo.Kimlik.LastName + "<br />";
                        MemberInfo2 += UserInfo.Kimlik.EvAdres + " " + UserInfo.Kimlik.N_Mahalle + " " + UserInfo.Kimlik.N_Ilce + "/" + UserInfo.Kimlik.N_KutukIl + "</td>";

                        int AvlCounter = 1;
                        foreach (Guarantor Kefil in UserInfo.Kefiller)
                        {
                            GuarantorInfo2 += "<tr>";
                            GuarantorInfo2 += "<td>" + AvlCounter.ToString() + ". Avalist:<br />";
                            GuarantorInfo2 += "Adres:</td>";
                            GuarantorInfo2 += "<td>" + Kefil.FirstName + " " + Kefil.LastName + "<br />";
                            GuarantorInfo2 += "" + Kefil.EvAdres + " " + Kefil.N_Mahalle + " " + Kefil.N_Ilce + "/" + Kefil.N_KutukIl + "</td>";
                            GuarantorInfo2 += "</tr>";
                            AvlCounter++;
                        }
                        #endregion

                        MessageBody = MessageBody.Replace("{FirstName}", UserInfo.Kimlik.FirstName).Replace("{LastName}", UserInfo.Kimlik.LastName).Replace("{ProductsTableVoucher}", tableVoucher).Replace("{ProductsTable}", table).Replace("{InstallmentCount}", InstallmentCount.ToString());
                        MessageBody = MessageBody.Replace("{PaymentAmount}", PaymentAmount.ToString("###,###,##0.00")).Replace("{VoucherNumber}", PaymentId.ToString()).Replace("{VoucherDate}", VoucherDate).Replace("{MemberInfo1}", MemberInfo1);
                        MessageBody = MessageBody.Replace("{GuarantorInfo1}", GuarantorInfo1).Replace("{Guarantor1FullName}", Guarantor1FullName).Replace("{Guarantor2FullName}", Guarantor2FullName).Replace("{MemberInfo2}", MemberInfo2).Replace("{GuarantorInfo2}", GuarantorInfo2);
                    }

                    try
                    {
                        Utils.SendMail(eStoreUser.Email, "", Parameters.OrderMailBccAddress, "Siparişiniz Alınmıştır", MessageBody + "<br /><br />" + ccoModel.ContractText, true);
                    }
                    catch (Exception ex)
                    {
                        Logger.Write(ex, "Exception");
                    }
                    if (ccoModel.VisitorRegistered)
                    {
                        eStoreUser.AccountType = 1;
                        eStoreUser.AccountId = 0;
                        eStoreUser.SelectedGuarantor1Id = 0;
                        eStoreUser.SelectedGuarantor2Id = 0;
                        eStoreUser.FirstName = "";
                        eStoreUser.LastName = "";
                        eStoreUser.UserName = "";
                        eStoreUser.Email = "";
                    }
                    return Content("<script>window.location='/Cart/Order/" + orderId.ToString() + "'</script>");
                    #endregion

                    #endregion
                }
            }

            #endregion

            ccoTempModel.SelectedAction = "";
            ccoModel.SelectedAction = "";
            return PartialView("GetCheckout", ccoModel);
        }

        #endregion


        #region CheckOutCustom
        [RequireHttps]
        public ActionResult CheckOutCustom()
        {
            if (!Parameters.AllowVisitorsToUsingCart && eStoreUser.AccountType == 1)
            {
                string url = "/Account/Login?ReturnUrl=/Cart/CheckOutCustom";
                return Redirect(url);
            }
            
            return View();
        }
        #endregion

        #region GetCheckOutCustom

        [Child]
        public ActionResult GetCheckOutCustom()
        {
            if (!Parameters.AllowVisitorsToUsingCart && eStoreUser.AccountType == 1)
            {
                string url = "/Account/Login?ReturnUrl=/Cart/CheckOutCustom";
                return Redirect(url);
            }

            var ccoModel = Get_ccoModelCustom();

            ccoModel.ContractTotalPrice = ccoModel.TotalPayment;
            ccoModel.UserId = eStoreUser.AccountId;
            ccoModel.UserType = eStoreUser.AccountType;
            ccoModel.ItemCount = 1;
            ccoModel.SelectedCargoCompanyId = 0;

            if (ccoModel.SelectedPos == 0)
            {
                ccoModel.SelectedPos = ccoModel.PosList.FirstOrDefault().PosId;
                ccoModel.PosInstallmentList = dbPos.GetInstallmentList(ccoModel.SelectedPos, ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard - ccoModel.CargoTotalPrice : ccoModel.TotalPayment, ccoModel.TotalPayment, ccoModel.CargoPrice, ccoModel.CargoPrice2);
                ccoModel.SelectedInstallment = ccoModel.PosInstallmentList.FirstOrDefault().InstallmentNumber;
                ccoModel.SelectedPosDescription = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Description;
                ccoModel.SelectedPosEnabled3D = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Enabled3D;
                ccoModel.Type3D = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Type3D;
            }

            if (Session["Error_3D"] != null)
            {
                ccoModel.Message4 = Session["Error_3D"].ToString();
                Session["Error_3D"] = null;
            }

            return PartialView("GetCheckOutCustom", ccoModel);
        }

        #endregion

        #region Get_ccoModelCustom

        private CartCheckOutModel Get_ccoModelCustom()
        {
            CartCheckOutModel ccoModel = new CartCheckOutModel();

            #region First & Last Name & Item Count

            ccoModel.UserName = eStoreUser.FirstName + " " + eStoreUser.LastName;
            ccoModel.UserId = eStoreUser.AccountId;
            ccoModel.ItemCount = eStoreUser.ItemCount;
            ccoModel.SelectedAction = "KrediKart";

            #endregion

            #region Cart Summary

            //ccoModel.Summary.TotalPrice = eStoreUser.TotalPrice;
            //ccoModel.Summary.TotalQty = eStoreUser.TotalQty;
            //ccoModel.Summary.ItemCount = eStoreUser.ItemCount;

            #endregion

            #region Cargo Summary

            ccoModel.CargoPrice = 0;
            ccoModel.CargoPrice2 = 0;
            ccoModel.CargoTotalPrice = 0;

            ccoModel.TotalPaymentWithTransfer = 0;
            #endregion

            #region Init Vars
            ccoModel.CardNumber1 = "";
            ccoModel.CardNumber2 = "";
            ccoModel.CardNumber3 = "";
            ccoModel.CardNumber4 = "";

            ccoModel.ValidMonth = 0;
            ccoModel.ValidYear = 0;
            ccoModel.CVV = "";
            ccoModel.CardOwnerName = "";
            ccoModel.PartialPayment = null;
            ccoModel.CustomPaymentCaptchaVerified = eStoreUser.CustomPaymentCaptchaVerified;
            ccoModel.AgreementChecked = 0;

            #endregion

            #region POS & Installment

            ccoModel.PosList = Parameters.PosListDDL; // dbPos.GetList();
            ccoModel.PosList = ccoModel.PosList.Where(o => o.PosVoucher == "M").ToList();

            if (ccoModel.SelectedPos > 0)
            {
                ccoModel.PosInstallmentList = dbPos.GetInstallmentList(ccoModel.SelectedPos, ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard - ccoModel.CargoTotalPrice : ccoModel.TotalPayment, ccoModel.TotalPayment, ccoModel.CargoPrice, ccoModel.CargoPrice2);
            }
            else
            {
                ccoModel.PosInstallmentList = new List<PosInstallment>();
            }

            ccoModel.BinList = Parameters.BinList;

            #endregion

            return ccoModel;
        }

        #endregion

        #region Get_ccoModelCustom with Parameter

        private CartCheckOutModel Get_ccoModelCustom(CartCheckOutModel ccoTempModel)
        {
            var ccoModel = Get_ccoModelCustom();

            ccoModel.UserId = eStoreUser.AccountId;
            ccoModel.AgreementChecked = ccoTempModel.AgreementChecked;

            #region Form Fields to New ccoModel !!!!

            ccoModel.FirstName = ccoTempModel.FirstName;
            ccoModel.LastName = ccoTempModel.LastName;
            ccoModel.Mobile = ccoTempModel.Mobile;
            ccoModel.TCKimlik = ccoTempModel.TCKimlik;

            ccoModel.PromoCode = "";
            ccoModel.Use3D = ccoTempModel.Use3D;
            ccoModel.IsTotalPayment = true;

            ccoModel.PartialPayment = 0;

            ccoModel.CargoWithInvoice = ccoTempModel.CargoWithInvoice;

            #region Credit Card Info

            ccoModel.CardNumber1 = ccoTempModel.CardNumber1;
            ccoModel.CardNumber2 = ccoTempModel.CardNumber2;
            ccoModel.CardNumber3 = ccoTempModel.CardNumber3;
            ccoModel.CardNumber4 = ccoTempModel.CardNumber4;

            ccoModel.ValidMonth = ccoTempModel.ValidMonth;
            ccoModel.ValidYear = ccoTempModel.ValidYear;
            ccoModel.CVV = ccoTempModel.CVV;
            ccoModel.CardOwnerName = ccoTempModel.CardOwnerName;

            #endregion

            ccoModel.PaymentType = PaymentTypes.KrediKart;

            ccoModel.SelectedPos = ccoTempModel.SelectedPos;
            ccoModel.SelectedInstallment = ccoTempModel.SelectedInstallment;
            ccoModel.SelectedCargoCompanyId = ccoTempModel.SelectedCargoCompanyId;

            ccoModel.OrderNote = ccoTempModel.OrderNote;

            #endregion

            #region Cargo & TotalPayment

            ccoModel.CargoPrice = 0;
            ccoModel.CargoPrice2 = 0;
            ccoModel.CargoTotalPrice = 0;


            ccoModel.TotalPayment = ccoTempModel.TotalPayment;

            ccoModel.TotalPaymentWithTransfer = 0;

            #endregion

            #region POS & Installment

            if (ccoModel.SelectedPos > 0)
            {
#warning PartialPayment yapılacak
                ccoModel.PosInstallmentList = dbPos.GetInstallmentList(ccoModel.SelectedPos, ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard - ccoModel.CargoTotalPrice : ccoModel.TotalPayment, ccoModel.TotalPayment, ccoModel.CargoPrice, ccoModel.CargoPrice2);
                ccoModel.SelectedPosDescription = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Description;
                ccoModel.SelectedPosEnabled3D = ccoModel.PosList.Where(p => p.PosId == ccoModel.SelectedPos).FirstOrDefault().Enabled3D;
            }
            else
            {
                ccoModel.PosInstallmentList = new List<PosInstallment>();
                ccoModel.SelectedPosDescription = "";
                ccoModel.SelectedPosEnabled3D = false;
            }

            #endregion

            ccoModel.Type3D = ccoModel.PosList.Where(p => p.PosId == ccoTempModel.SelectedPos).FirstOrDefault().Type3D;
            if (ccoModel.Type3D == "Zorunlu")
            {
                ccoModel.Use3D = true;
            }
            else if (ccoModel.Type3D == "Yok")
            {
                ccoModel.Use3D = false;
            }

            return ccoModel;
        }

        #endregion

        #region Refresh CheckoutCustom

        [Child]
        public ActionResult RefreshCustom(CartCheckOutModel ccoTempModel)
        {
            var ccoModel = Get_ccoModelCustom(ccoTempModel);
            bool PaymentSucceeded = false;
            decimal Payment = 0;
            bool dataOK = true;
            decimal KrediKartIndirimi = 0;
            decimal KomisyonOrani = 0;
            decimal KampanyaKomisyonOrani = 0;
            string OrderPaymentType = "";
            var parsint = 0;


            if (!eStoreUser.CustomPaymentCaptchaVerified)
            {
                dataOK = false;
                ccoModel.Message6 = "<span class=\"checkOut-Error-Text\">Doğrulama kodu eksik girilmiş ya da hiç girilmemiş. Tekrar deneyin.</span>";
            }
            else
            {
                eStoreUser.CustomPaymentCaptchaVerified = true;
                ccoModel.CustomPaymentCaptchaVerified = true;
            }
            if (ccoModel.TotalPayment <= 0)
            {
                dataOK = false;
                ccoModel.Message8 = "<span class=\"checkOut-Error-Text\">Ödeme miktarı girilmemiş.</span>";
            }

            #region Prepare Contract Price

            if (ccoModel.PaymentType == PaymentTypes.KrediKart)
            {
                if (ccoModel.SelectedInstallment == 0)
                {
                    ccoModel.SelectedInstallment = 1;
                }
                if (ccoModel.SelectedPos == 0)
                {
                    ccoModel.ContractTotalPrice = ccoModel.TotalPayment;
                }
                else
                {
                    PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                    if (pi == null)
                    {
                        ccoModel.SelectedInstallment = 1;
                        pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                    }
                    if (pi != null)
                    {
                        ccoModel.ContractTotalPrice = pi.TotalInterestPrice;
                    }
                    else
                    {
                        ccoModel.ContractTotalPrice = ccoModel.TotalPayment;
                    }
                }
            }

            #endregion

            string VoucherComment = "";
            decimal PriceToInsert = 0;

            //ccoTempModel.SelectedAction = "110";
            if (ccoTempModel.SelectedAction == "110" || ccoTempModel.SelectedAction == "KrediKart")
            {
                ccoTempModel.SelectedAction = "110";
                OrderPaymentType = "K";

                #region Payment Type - Credit Card

                #region Is Data OK

                if (string.IsNullOrEmpty(ccoModel.FirstName) || string.IsNullOrEmpty(ccoModel.LastName) || string.IsNullOrEmpty(ccoModel.TCKimlik) || string.IsNullOrEmpty(ccoModel.Mobile))
                {
                    dataOK = false;
                    ccoModel.Message7 = "<span class=\"checkOut-Error-Text\">Borçlu Bilgilerini Giriniz.</span>";
                }
                else if (!TCKimlikMod(ccoModel.TCKimlik))
                {
                    dataOK = false;
                    ccoModel.Message7 = "<span class=\"checkOut-Error-Text\">Eksik veya hatalı bir TC Kimlik numarası girdiniz.</span>";
                }

                var CardType = !string.IsNullOrEmpty(ccoModel.CardNumber1) ? ccoModel.CardNumber1.Substring(0, 1) : "";
                if (CardType == "3")
                {
                    ccoModel.CardNumber = ccoModel.CardNumber1 + ccoModel.CardNumber2 + ccoModel.CardNumber3;
                }
                else
                {
                    ccoModel.CardNumber = ccoModel.CardNumber1 + ccoModel.CardNumber2 + ccoModel.CardNumber3 + ccoModel.CardNumber4;
                }

                long cardNumber = 0;
                string cvv = "0";
                try
                {
                    cardNumber = long.Parse(ccoModel.CardNumber);
                }
                catch
                {
                    cardNumber = 0;
                }
                try
                {
                    cvv = ccoModel.CVV;
                }
                catch
                {
                    cvv = "0";
                }

                cvv = ccoModel.CVV;

                /*Bin Str*/
                var BinSTR = "";
                if (ccoModel.CardNumber.Length >= 15)
                {
                    BinSTR = ccoModel.CardNumber.Substring(0, 6);
                }
                /*Bin Str*/

                if (!(ccoModel != null && ccoModel.CardNumber != null && ((CardType == "3" && ccoModel.CardNumber.Length == 15) || (ccoModel.CardNumber.Length == 16)) && cardNumber > 0 && cvv != null && cvv.ToString().Length == 3 && ccoModel.ValidMonth > 0 && ccoModel.ValidYear > 0 && !String.IsNullOrEmpty(ccoModel.CardOwnerName)))
                {
                    dataOK = false;
                    ccoModel.Message4 = "<span class=\"checkOut-Error-Text\">Kart bilgilerini kontrol ediniz.</span>";
                }

                Payment = ccoModel.ContractTotalPrice;


                PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                PriceToInsert = pi.TotalInterestPrice;

                PaymentUtils oPos = new PaymentUtils();

                Pos aPos = new Pos();

                if (ccoModel.SelectedInstallment < 2)
                {
                    #region Tek Çekim Default POS kullanımı


                    if (Parameters.UseSelfPosOneInstallment && !string.IsNullOrEmpty(BinSTR) && ccoModel.BinList.Where(o => o.PosVoucher == "M").Select(o => o.Bin.ToString()).Contains(BinSTR))
                    {
                        //tek çekim
                        var selectedPosByBin = ccoModel.BinList.Where(o => o.PosVoucher == "M" && o.Bin.ToString() == BinSTR).FirstOrDefault().PosId;
                        aPos = PosProcess.GetPos(selectedPosByBin); // dbPos.Get(Parameters.DefaultPosId);
                        if (aPos == null)
                        {
                            Logger.Write("Seçilen POS bulunamadı BIN listesinde eksik olabilir = " + selectedPosByBin.ToString() + " BIN: " + BinSTR + ". Seçilen POS ile işleme devam ediliyor", "Exception");
                            aPos = PosProcess.GetPos(ccoModel.SelectedPos); // dbPos.Get(ccoModel.SelectedPos);
                        }
                    }
                    else if (Parameters.DefaultPosIdCustom > 0)
                    {
                        aPos = PosProcess.GetPos(Parameters.DefaultPosIdCustom); // dbPos.Get(Parameters.DefaultPosId);
                        if (aPos == null)
                        {
                            Logger.Write("Varsayılan POS bulunamadı 2027 nolu referans = " + Parameters.DefaultPosIdCustom.ToString() + ". Seçilen POS ile işleme devam ediliyor", "Exception");
                            aPos = PosProcess.GetPos(ccoModel.SelectedPos); // dbPos.Get(ccoModel.SelectedPos);
                        }
                    }
                    #endregion
                }
                else
                {
                    aPos = PosProcess.GetPos(ccoModel.SelectedPos); // dbPos.Get(ccoModel.SelectedPos);
                }

                ccoModel.PosInstallmentList = dbPos.GetInstallmentList(ccoModel.SelectedPos, ccoModel.TotalPaymentWithCreditCard > 0 ? ccoModel.TotalPaymentWithCreditCard - ccoModel.CargoTotalPrice : ccoModel.TotalPayment, ccoModel.TotalPayment, ccoModel.CargoPrice, ccoModel.CargoPrice2);
                pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
                PriceToInsert = pi.TotalInterestPrice;

                if (!ccoModel.Use3D && Parameters.Use3DPayment && aPos.Enabled3D && ccoModel.ContractTotalPrice > Parameters.Force3DPaymentPriceMinLimit)
                {
                    dataOK = false;
                    ccoModel.Message4 = "<span class=\"checkOut-Error-Text\">Toplam Tutar Kontrol Limiti Üzerinde, 3D Ödeme Seçimi Yapınız.</span>";
                }

                #endregion

                if (dataOK)
                {
                    #region POS

                    // Test için Start
                    //POSResult posResult = new POSResult();
                    //posResult.ApproveCode = aPos.ApproveCode;
                    //posResult.OrderID = "ORID1234546356456546";
                    // Test için End

                    if (ccoModel.Use3D)
                    {
                        #region Start 3D Validation

                        Session["OMAY_Payment_CCNo"] = ccoModel.CardNumber;
                        Session["OMAY_Payment_Month"] = ccoModel.ValidMonth;
                        Session["OMAY_Payment_Year"] = ccoModel.ValidYear;
                        Session["OMAY_Payment_CVV"] = cvv;
                        Session["OMAY_Payment_CardOwner"] = ccoModel.CardOwnerName;
                        string sessionId = Guid.NewGuid().ToString("N");
                        Session["OMAY_Payment_SessionId"] = sessionId;

                        Response.Clear();
                        string strTimeStamp = Parameters.Now.ToString("yyyyMMddHHmmss");
                        string strOrderID = Guid.NewGuid().ToString("N"); //"ORID" + eStoreUser.AccountId.ToString("000000") + strTimeStamp;

                        //dbPayment.Insert(sessionId, eStoreUser.AccountId, Parameters.Now, "QUE", 1, pi.TotalInterestPrice, pi.TotalInterestPrice, aPos.PosId, (short)ccoModel.SelectedInstallment, ccoModel.SelectedCargoCompanyId, ccoModel.CargoAddressId, ccoModel.InvoiceAddressId, strOrderID, Utils.UserIP, "");

                        string formHtml = oPos.Start3D(aPos, eStoreUser.Email, sessionId, strTimeStamp, strOrderID, ccoModel.SelectedInstallment.ToString(), eStoreUser.AccountId, ccoModel.CardNumber, ccoModel.ValidMonth, ccoModel.ValidYear, cvv, ccoModel.CardOwnerName, pi.TotalInterestPrice, ccoModel.InvoiceAddress);

                        Logger.Write("Sent Form : " + formHtml, "Trace");

                        return Content(formHtml);

                        #endregion
                    }


                    POSResult posResult = oPos.Send(aPos, eStoreUser.Email, ccoModel.SelectedInstallment.ToString(), eStoreUser.AccountId, ccoModel.CardNumber, ccoModel.ValidMonth, ccoModel.ValidYear, cvv, ccoModel.CardOwnerName, pi.TotalInterestPrice, false, "", "", ccoModel.InvoiceAddress);

                    VoucherComment = posResult.OrderID ?? "";

                    #region Log XML

                    try
                    {
                        Logger.Write(aPos.BankName + " -> " + posResult.RequestXMLString.Replace(ccoModel.CardNumber, ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4)), "Trace");
                    }
                    catch
                    { }

                    try
                    {
                        Logger.Write(aPos.BankName + " -> " + posResult.ResponseXMLString.Replace(ccoModel.CardNumber, ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4)), "Trace");
                    }
                    catch
                    { }

                    #endregion

                    #endregion

                    if (posResult.ApproveCode == aPos.ApproveCode)
                    {
                        #region Success - Credit Card Checkout

                        PaymentSucceeded = true;

                        //PaymentId = dbVoucher.Insert(eStoreUser.AccountId, (short)PaymentTypes.KrediKart.GetHashCode(), true, false, 0, Parameters.Now.AddYears(10), eStoreUser.AccountId, pi.TotalInterestPrice, true, VoucherComment, false, ccoModel.CardOwnerName + " - " + ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4), aPos.PosId, (short)ccoModel.SelectedInstallment, aPos.BankId, Parameters.Now);

                        //if (ccoModel.SelectedInstallment <= 1) HavaleEFTIndirimi = Parameters.CreditCardDiscount - 1;
                        //else HavaleEFTIndirimi = (1 - pi.CommissionRate) * 100; // - değer olacak

                        KomisyonOrani = pi.CommissionRate;
                        KampanyaKomisyonOrani = pi.CampaignCommissionRate;


                        if (ccoModel.SelectedInstallment > 1)
                        {
                            KrediKartIndirimi = Parameters.CreditCardDiscount;
                        }

                        #endregion
                    }
                    else
                    {
                        #region Error - Credit Card Checkout

                        ccoModel.Message4 = "<span class=\"checkOut-Error-Text\">" + posResult.Explanation + " - " + posResult.Message + "</span>";

                        #endregion
                    }
                }

                #endregion


                #region PaymentSucceeded

                if (PaymentSucceeded)
                {
                    #region Tüm Ödeme Tamamlandı

                    string MessageBody = "";

                    if (ccoTempModel.SelectedAction == "110" || ccoTempModel.SelectedAction == "KrediKart")
                    {
                        MessageBody = dbRefs.GetRef5(123);
                    }
                    int insertResult = 0;
                    string cardNumberToInsert = ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4);
                    string bankNameToInsert = aPos.BankName;
                    string cardOwnerFirstName = ccoModel.CardOwnerName;
                    DateTime NowDateTime = DateTime.Now;
                    string NowDateTimeStr = NowDateTime.ToString("dd-MM-yyyy HH:mm:ss");
                    //VoucherComment = Orderno
                    //OrgPriceToInsert
                    //PriceToInsert

                    try
                    {
                        insertResult = dbCart.CreateManualPos(ccoModel.FirstName, ccoModel.LastName, ccoModel.TCKimlik, ccoModel.Mobile, ccoModel.CardOwnerName, cardNumberToInsert, bankNameToInsert, VoucherComment, ccoModel.TotalPayment, PriceToInsert, ccoModel.SelectedInstallment, DateTime.Now, HttpContext.Request.UserHostAddress);
                    }
                    catch (Exception ex)
                    {
                        Logger.Write(ex, "Exception");
                    }

                    string MessageTitle = insertResult == 1 ? "Ödeme Alıdı, Kayıt Eklendi." : "Ödeme Alındı, Kayıt Eklenemedi.";
                    MessageBody = MessageBody.Replace("{FirstName}", ccoModel.FirstName).Replace("{LastName}", ccoModel.LastName).Replace("{TCKimlik}", ccoModel.TCKimlik).Replace("{Mobile}", ccoModel.Mobile).Replace("{CardOwnerName}", ccoModel.CardOwnerName).Replace("{CardNumber}", cardNumberToInsert).Replace("{OrderNo}", VoucherComment).Replace("{Date}", NowDateTimeStr);
                    MessageBody = MessageBody.Replace("{PaymentAmount}", ccoModel.TotalPayment.ToString("###,###,##0.00")).Replace("{PaidAmount}", PriceToInsert.ToString("###,###,##0.00")).Replace("{InstallmentCount}", ccoModel.SelectedInstallment.ToString());
                    try
                    {
                        Utils.SendMail(Parameters.CustomCheckOutMailAddress, "", Parameters.OrderMailBccAddress, MessageTitle, MessageBody + "<br /><br />", true);
                    }
                    catch (Exception ex)
                    {
                        Logger.Write(ex, "Exception");
                    }

                    return Content("<script>window.location.href='/Cart/CustomPaymentSucceeded'</script>");
                    #endregion
                }
            }

                #endregion

            return PartialView("GetCheckoutCustom", ccoModel);
        }

        #endregion

        #region CheckoutCustomCaptcha

        public ActionResult CheckoutCustomCaptcha()
        {
            return View();
        }

        [HttpPost]
        public ActionResult CheckoutCustomCaptcha(int id)
        {
            if (!eStoreUser.CustomPaymentCaptchaVerified && !this.IsCaptchaVerify("Hatalı Doğrulama Kodu."))
            {
                return JavaScript("hataliCaptcha();");
            }
            else
            {
                eStoreUser.CustomPaymentCaptchaVerified = true;
                return JavaScript("basariliCaptcha();");
            }
        }

        #endregion


        #region Get Summary

        [AllowAnonymous]
        [Child]
        public ActionResult GetSummary()
        {
            Summary cartSummary = new Summary();

            cartSummary.TotalQty = eStoreUser.TotalQty;
            cartSummary.TotalPrice = eStoreUser.TotalPrice;
            cartSummary.InstallmentPrice = eStoreUser.InstallmentPrice;
            cartSummary.InstallmentTax = eStoreUser.InstallmentTax;

            return PartialView("GetSummary", cartSummary);
        }

        [AllowAnonymous]
        [Child]
        public ActionResult GetSummary2()
        {
            Summary cartSummary = new Summary();

            cartSummary.TotalQty = eStoreUser.TotalQty;
            cartSummary.TotalPrice = eStoreUser.TotalPrice;
            cartSummary.InstallmentPrice = eStoreUser.InstallmentPrice;
            cartSummary.InstallmentTax = eStoreUser.InstallmentTax;
            cartSummary.TotalPriceCreditCard = Math.Round(eStoreUser.TotalPrice / Parameters.CreditCardDiscount, 2);

            return PartialView("GetSummary2", cartSummary);
        }

        #endregion

        #region Insert

        [Child]
        [AllowAnonymous]
        public ActionResult Insert(int? id, int? qty, bool? installment, string variantValue = "")
        {

            if (!installment.HasValue)
            {
                installment = false;
            }
            if (!qty.HasValue || (int)qty <= 0)
            {
                qty = 1;
            }

            if (eStoreUser.AccountId > 0 && eStoreUser.AccountType == 0)
            {

                #region Stok Kontrol
                Product product = dbProduct.Get((int)id, eStoreUser.AccountId);
                CartModel cartModel = new CartModel();
                cartModel.Products = dbCart.GetList(eStoreUser.AccountId, 0);

                var productStock = product.InStockDepo;
                var productInCart = 0;
                if (cartModel.Products.Where(o => o.ProductId == id).Count() > 0)
                {
                    productInCart = (int)cartModel.Products.Where(o => o.ProductId == id).FirstOrDefault().Qty;
                }
                var productToCartAvailable = productStock - productInCart;

                if (product.CheckStock && !Parameters.AllowEndedProducts && qty > 0)
                {
                    if (productStock < 1)
                    {
                        return JavaScript("<script>alert('Bu ürün stoklarımızda kalmamıştır.');$('#cart').load('/Cart/GetSummary2', {}); $('#sepetMinimalContent').load('/Cart/GetMinimal', { showPhotos: true });</script>");
                    }
                    if (productToCartAvailable < (int)qty)
                    {
                        if (productToCartAvailable <= 0)
                        {
                            return JavaScript("<script>alert('Stoklarımızda " + (Convert.ToInt32(productStock)).ToString() + " adet bulunan ürünün tümünü sepetinize eklediğinizden daha fazla ekleyemezsiniz.');$('#cart').load('/Cart/GetSummary2', {}); $('#sepetMinimalContent').load('/Cart/GetMinimal', { showPhotos: true });</script>");
                        }
                        else
                        {
                            //return JavaScript("<script>alert('\'" + product.ProductName + "\' ürününden en fazla " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet sipariş verebilirsiniz.');</script>");
                            return JavaScript("<script>if (confirm('\"" + product.ProductName + "\" ürününden sepetinize en fazla " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet ekleyebilirsiniz. " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet eklemek için Tamam\\'a tıklayın.')) { $('#cart').delay(800).load('/Cart/Insert', { id: " + id.ToString() + ", qty: " + (Convert.ToInt32(productToCartAvailable)).ToString() + ", installment: '" + installment.ToString() + "', variantValue: '" + variantValue.ToString() + "' }); } $('#cart').load('/Cart/GetSummary2', {}); $('#sepetMinimalContent').load('/Cart/GetMinimal', { showPhotos: true });</script>");
                        }
                    }
                }
                #endregion

                if (id.HasValue)
                {
                    dbCart.Insert(eStoreUser.AccountId, 0, 0, (int)id, (int)qty, 0, false, (bool)installment, Parameters.Now, variantValue, 0);
                }

                RefreshCartSummary();

                return GetSummary2();
            }
            else
            {
                if (!Parameters.AllowVisitorsToUsingCart)
                {
                    if (id.HasValue)
                    {
                        eStoreUser.ProductIdToAddCart = (int)id;
                        eStoreUser.ProductVariantToAddCart = (string)variantValue;
                        eStoreUser.InstallmentSelected = (bool)installment;
                        eStoreUser.ProductAmountToAddCart = (int)qty;
                    }
                    return JavaScript("<script>window.location='" + Parameters.WebSiteSecureUrl + "/Account/Login';</script>");
                }
                else
                {
                    if (id.HasValue)
                    {
                        eStoreUser.ProductIdToAddCart = (int)id;
                        if (eStoreUser.AccountId < 1)
                        {
                            eStoreUser.AccountId = dbAccount.InsertVisitor(HttpContext.Request.UserHostAddress);
                            eStoreUser.AccountType = 1;
                        }
                        #region Stok Kontrol
                        Product product = dbProduct.Get((int)id, eStoreUser.AccountId);
                        CartModel cartModel = new CartModel();
                        cartModel.Products = dbCart.GetList(eStoreUser.AccountId, 1);

                        var productStock = product.InStockDepo;
                        var productInCart = 0;
                        if (cartModel.Products.Where(o => o.ProductId == id).Count() > 0)
                        {
                            productInCart = (int)cartModel.Products.Where(o => o.ProductId == id).FirstOrDefault().Qty;
                        }
                        var productToCartAvailable = productStock - productInCart;

                        if (product.CheckStock && !Parameters.AllowEndedProducts && qty > 0)
                        {
                            if (productStock < 1)
                            {
                                return JavaScript("<script>alert('Bu ürün stoklarımızda kalmamıştır.');$('#cart').load('/Cart/GetSummary2', {}); $('#sepetMinimalContent').load('/Cart/GetMinimal', { showPhotos: true });</script>");
                            }
                            if (productToCartAvailable < (int)qty)
                            {
                                if (productToCartAvailable <= 0)
                                {
                                    return JavaScript("<script>alert('Stoklarımızda " + (Convert.ToInt32(productStock)).ToString() + " adet bulunan ürünün tümünü sepetinize eklediğinizden daha fazla ekleyemezsiniz.');$('#cart').load('/Cart/GetSummary2', {}); $('#sepetMinimalContent').load('/Cart/GetMinimal', { showPhotos: true });</script>");
                                }
                                else
                                {
                                    //return JavaScript("<script>alert('\'" + product.ProductName + "\' ürününden en fazla " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet sipariş verebilirsiniz.');</script>");
                                    return JavaScript("<script>if (confirm('\"" + product.ProductName + "\" ürününden sepetinize en fazla " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet ekleyebilirsiniz. " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet eklemek için Tamam\\'a tıklayın.')) { $('#cart').delay(800).load('/Cart/Insert', { id: " + id.ToString() + ", qty: " + (Convert.ToInt32(productToCartAvailable)).ToString() + ", installment: '" + installment.ToString() + "', variantValue: '" + variantValue.ToString() + "' }); } $('#cart').load('/Cart/GetSummary2', {}); $('#sepetMinimalContent').load('/Cart/GetMinimal', { showPhotos: true });</script>");
                                }
                            }
                        }
                        #endregion

                        dbCart.Insert(eStoreUser.AccountId, 0, 0, (int)id, (int)qty, 0, false, (bool)installment, Parameters.Now, variantValue, 1);
                    }
                    RefreshCartSummary();
                    return GetSummary2();
                }
            }
        }

        [Child]
        public ActionResult Insert2(int ListOwnerId, long ListId, int ProductId, int Qty)
        {
            CartModel cartModel = new CartModel();
            if (ListOwnerId > 0 && ListId > 0 && ProductId > 0 && Qty > 0)
            {
                //variant giricez
                dbCart.Insert(eStoreUser.AccountId, ListOwnerId, ListId, ProductId, Qty, 0, false, false, Parameters.Now, "", 0);
            }

            RefreshCartSummary();

            return GetSummary2();
        }

        #endregion

        #region Update

        [Child]
        public ActionResult Update(int ListOwnerId, int listId, int id, int? qty, int? position, bool? showMsg)
        {
            ViewData.ModelState.Clear();
            #region Stok Kontrol
            Product product = dbProduct.Get((int)id, eStoreUser.AccountId);
            CartModel cartModel = new CartModel();
            cartModel.Products = dbCart.GetList(eStoreUser.AccountId, eStoreUser.AccountType);

            var productStock = product.InStockDepo;
            var productInCart = 0;
            if (cartModel.Products.Where(o => o.ProductId == id).Count() > 0)
            {
                productInCart = (int)cartModel.Products.Where(o => o.ProductId == id).FirstOrDefault().Qty;
            }
            var productToCartAvailable = productStock - productInCart;
            var added = qty - productInCart;
            #endregion

            if (productStock < 1 && product.CheckStock && !Parameters.AllowEndedProducts && qty > 0 && qty > productInCart)
            {
                ViewData["cartMessage"] = "<script>alert('Bu ürün stoklarımızda kalmamıştır.');</script>";
                //return JavaScript("");
            }
            else if (productToCartAvailable < (int)added && product.CheckStock && !Parameters.AllowEndedProducts && qty > 0 && qty > productInCart)
            {
                if (productToCartAvailable <= 0)
                {
                    ViewData["cartMessage"] = "<script>alert('Stoklarımızda " + (Convert.ToInt32(productStock)).ToString() + " adet bulunan ürünün tümünü sepetinize eklediğinizden daha fazla ekleyemezsiniz.');</script>";
                    //return JavaScript("");
                }
                else
                {
                    ViewData["cartMessage"] = "<script>if (confirm('\"" + product.ProductName + "\" ürününden sepetinize en fazla " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet ekleyebilirsiniz. " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet eklemek için Tamam\\'a tıklayın.')) { $('.contentCart').load('/Cart/Update', { ListOwnerId: 0, listId: 0, id: " + id.ToString() + ", qty: " + (Convert.ToInt32(productStock)).ToString() + " }); } </script>";
                    //return JavaScript("<script>alert('\'" + product.ProductName + "\' ürününden en fazla " + (Convert.ToInt32(productToCartAvailable)).ToString() + " adet sipariş verebilirsiniz.');</script>");
                    //return JavaScript("");
                }
            }
            else if (eStoreUser != null && eStoreUser.AccountId > 0 && id > 0 && listId >= 0 && qty.HasValue)
            {
                dbCart.Update(eStoreUser.AccountId, eStoreUser.AccountType, ListOwnerId, listId, id, (int)qty, 0, false, Parameters.Now);
            }

            if (showMsg.HasValue || showMsg == false)
            {
                ViewData["cartMessage"] = "";
            }

            if (position.HasValue && position == 1)
            {
                return GetMinimal(showPhotos: true, ShowAcrIcrLinks: true);
            }
            else if (position.HasValue && position == 2)
            {
                return GetMinimal(showPhotos: false, ShowAcrIcrLinks: true);
            }
            RefreshCartSummary();
            return Get();
        }

        #endregion

        #region Remove

        [Child]
        public ActionResult Remove(int ListOwnerId, int listId, int id)
        {
            if (eStoreUser != null && eStoreUser.AccountId > 0)
            {
                dbCart.Delete(eStoreUser.AccountId, eStoreUser.AccountType, ListOwnerId, listId, id);
            }

            RefreshCartSummary();

            return Get();
        }

        #endregion

        #region RefreshCartSummary

        public void RefreshCartSummary()
        {
            if (eStoreUser.AccountId > 0)
            {
                CartSummary summary = dbCart.GetSummary(eStoreUser.AccountId, eStoreUser.AccountType);
                eStoreUser.TotalQty = summary.TotalQty;
                eStoreUser.TotalPrice = summary.TotalPrice;
                eStoreUser.ItemCount = summary.ItemCount;
                eStoreUser.Tax = summary.Tax;
                eStoreUser.InstallmentPrice = summary.InstallmentPrice;
                eStoreUser.InstallmentTax = summary.InstallmentTax;
            }
            else
            {
                eStoreUser.TotalQty = 0;
                eStoreUser.TotalPrice = 0;
                eStoreUser.Tax = 0;
                eStoreUser.ItemCount = 0;
                eStoreUser.InstallmentPrice = 0;
                eStoreUser.InstallmentTax = 0;
            }
        }

        #endregion

        #region AddToCart

        public ActionResult AddToCart(AddToCartModel atcModel, int? UserId, long? ListId, int? ProductId)
        {
            if (UserId.HasValue && string.IsNullOrEmpty(atcModel.SelectedButton))
            {
                AddToCartModel addtoCartModel = new AddToCartModel();
                addtoCartModel.UserId = (int)UserId;
                addtoCartModel.ListId = (long)ListId;
                addtoCartModel.ProductId = (int)ProductId;

                Product product = dbProduct.Get((int)ProductId, (int)UserId);
                addtoCartModel.ProductName = product.ProductName;
                addtoCartModel.ShowNameOnList = true;

                return PartialView("AddToCart", addtoCartModel);
            }
            else
            {
                string Message = "";
                if (atcModel.SelectedButton == "Buy")
                {
                    //variant giricez
                    dbCart.Insert(eStoreUser.AccountId, atcModel.UserId, atcModel.ListId, atcModel.ProductId, atcModel.Qty, 0, atcModel.ShowNameOnList, false, Parameters.Now, "", 0);
                    Message = "<font color=green>Ürün sepetinize eklendi.</font>";
                }
                else if (atcModel.SelectedButton == "Support")
                {
                    //variant giricez
                    dbCart.Insert(eStoreUser.AccountId, atcModel.UserId, atcModel.ListId, atcModel.ProductId, 0, (decimal)atcModel.SupportPayment, atcModel.ShowNameOnList, false, Parameters.Now, "", 0);
                    Message = "<font color=green>Destek miktarı sepetinize eklendi.</font>";
                }
                RefreshCartSummary();
                return Content(Message);
            }
        }

        #endregion

        #region PaymentSucceeded

        public ActionResult PaymentSucceeded(int id)
        {
            if (eStoreUser.AccountId > 0 && id > 0)
            {
                PaymentSucceededModel psm = new PaymentSucceededModel();
                psm.Messages = new List<PaymentSucceededMessage>();

                psm.OrderId = id;
                psm.Payments = dbVoucher.GetOrderPayments(eStoreUser.AccountId, id);
                if (psm.Payments != null && psm.Payments.Count > 0)
                {
                    psm.Link = "<a href='/Order/Detail/" + id.ToString() + "'>Sipariş Detayı İçin Tıklayınız.</a>";
                    foreach (Voucher payment in psm.Payments)
                    {
                        if (payment.TypeId > 100)
                        {
                            PaymentSucceededMessage psMessage = new PaymentSucceededMessage();
                            psMessage.PaymentType = payment.TypeId;

                            if (payment.TypeId == 110) { psMessage.Message = dbRefs.GetRef5(102); }
                            else if (payment.TypeId == 120) { psMessage.Message = dbRefs.GetRef5(100); }
                            else if (payment.TypeId == 160) { psMessage.Message = dbRefs.GetRef5(101); }
                            else if (payment.TypeId == 170) { psMessage.Message = dbRefs.GetRef5(103); }
                            else if (payment.TypeId == 180) { psMessage.Message = dbRefs.GetRef5(104); }

                            psm.Messages.Add(psMessage);

                        }
                        psm.PaymentDate = payment.CreateDate;
                    }

                    #region UCUZU TrustedShop

                    if (eStoreUser.UTMReferral == "UCUZU" && !string.IsNullOrEmpty(Parameters.UcuzuWebAPIKey) && Parameters.UcuzuTrusterdShopEnabled)
                    {
                        try
                        {
                            TrustedShop Client = new TrustedShop(Parameters.UcuzuWebAPIKey);

                            Client.SetEmail(eStoreUser.Email);

                            IList<OrderDetail> orderDetails = dbOrder.GetDetail(eStoreUser.AccountId, psm.OrderId);
                            if (orderDetails != null && orderDetails.Count > 0)
                            {
                                foreach (OrderDetail od in orderDetails)
                                {
                                    Client.AddProduct(od.ProductName);
                                }
                            }
                            psm.UcuzuTrustedShopScript = Client.Send();
                        }
                        catch (Exception Ex)
                        {
                            psm.UcuzuTrustedShopScript = "";
                            Logger.Write(Ex, "Exception");
                        }
                    }
                    else
                    {
                        psm.UcuzuTrustedShopScript = "";
                    }

                    #endregion

                    return PartialView("PaymentSucceeded", psm);
                }
                return Content("");
            }
            else
            {
                //Üyeliksiz alışveriş yapanlara bilgi vermemiz lazım burada.
                return Content("<h3>Siparişiniz alınmıştır. Teşekkür ederiz. </h3>");
            }
        }

        #endregion

        #region CustomPaymentSucceeded

        public ActionResult CustomPaymentSucceeded()
        {
            return View();
        }

        #endregion

        #region BankSuccess

        [AllowAnonymous]
        public ActionResult BankSuccess(int id)
        {
            #region Log

            Logger.Write("BankSuccess : " + id.ToString(), "Trace");
            Logger.Write("BankSuccess Form : " + Request.Form.ToString(), "Trace");

            NameValueCollection nvColleciton = Request.Form;

            string sesbil = Request.Form["sesbil"] ?? Session["OMAY_Payment_SessionId"].ToString();

            string cc = Session["OMAY_Payment_CCNo"].ToString();
            short month = (short)Session["OMAY_Payment_Month"];
            short year = (short)Session["OMAY_Payment_Year"];
            string cvv = Session["OMAY_Payment_CVV"].ToString();
            string cowner = Session["OMAY_Payment_CardOwner"].ToString();

            //Logger.Write(Session["OMAY_Payment_CCNo"] != null ? Session["OMAY_Payment_CCNo"] : "no session", "Trace");
            //Logger.Write(Session["OMAY_Payment_Month"] != null ? Session["OMAY_Payment_Month"] : "no session", "Trace");
            //Logger.Write(Session["OMAY_Payment_Year"] != null ? Session["OMAY_Payment_Year"] : "no session", "Trace");
            //Logger.Write(Session["OMAY_Payment_CVV"] != null ? Session["OMAY_Payment_CVV"] : "no session", "Trace");
            Logger.Write(Session["OMAY_Payment_CardOwner"] != null ? Session["OMAY_Payment_CardOwner"] : "no session", "Trace");

            Session["OMAY_Payment_CCNo"] = null;
            Session["OMAY_Payment_Month"] = null;
            Session["OMAY_Payment_Year"] = null;
            Session["OMAY_Payment_CVV"] = null;
            Session["OMAY_Payment_CardOwner"] = null;

            bool hatali;
            hatali = false;
            string errorDetail = "";

            #endregion

            #region Check Payment And Pos

            Payment payment = dbPayment.Get(sesbil);
            PaymentUtils oPos = new PaymentUtils();
            Pos aPos = dbPos.Get(id);

            #endregion

            #region Payment or Pos NOT Found

            if (payment == null || aPos == null)
            {
                Logger.Write("Payment yada Pos Bulunamadı!", "Trace");
                Session["Error_3D"] = "<span class=\"checkOut-Error-Text\">Ödeme yada Pos Bulunamadı</span>";

                return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Checkout/" + "'</script>");
            }

            #endregion

            #region Accounts NOT Match

            if (payment.UserId != eStoreUser.AccountId)
            {
                Logger.Write("Üye hesapları farklı!", "Trace");
                Session["Error_3D"] = "<span class=\"checkOut-Error-Text\">Üye hesapları farklı</span>";

                return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Checkout/" + "'</script>");
            }

            #endregion

            #region payment.Status != QUE

            if (payment.Status != "QUE")
            {
                Logger.Write("Bekleyen 3D Ödemesi Bulunamadı!", "Trace");
                Session["Error_3D"] = "<span class=\"checkOut-Error-Text\">Bekleyen 3D Ödemesi Bulunamadı</span>";

                return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Checkout/" + "'</script>");
            }

            #endregion

            POSResult posResult = new POSResult();

            string cavv = "";
            string eci = "";

            if (aPos.PosGroup == 4)
            {
                ArenaHelper helper = new ArenaHelper();
                var arenacheck = helper.Complete3dT(aPos.StoreNo, aPos.ApiUserName, "https://www.paynet.com.tr/connact/iodeme.asmx", aPos.UserId, aPos.TerminalId);

                if (arenacheck != null)
                {

                    Logger.Write("Hata Kodu!" + arenacheck.error_code, "Trace");
                    Session["Error_3D"] = "<span class=\"checkOut-Error-Text\">" + arenacheck.error_text + "</span>";
                    //Response.Write("errorCode : " + arenacheck.error_code);
                    //Response.Write("errorText : " + arenacheck.error_text);
                    //Response.Write("xactID : " + arenacheck.xactID);
                    //Response.Write("resultText : " + arenacheck.result_text);
                    //Response.Write("type : " + arenacheck.type.ToString());
                    if (arenacheck.result_text == "OK")
                    {
                        posResult.ApproveCode = "00";

                        posResult.OrderID = payment.OrderId;
                        posResult.Explanation = "İşlem Başarılı";

                        //Response.Write("transactionCode : " + arenacheck.referencecode.ToString());
                        //Response.Write("authorizationCode : " + arenacheck.authorizationcode);
                    }
                }
                else
                {
                    errorDetail = "3D Doğrulanamadı : ";
                    hatali = true;
                }
            }


            if (aPos.PosGroup == 5)
            {
                var response = AluResponse.FromHttpRequest(System.Web.HttpContext.Current.Request);
                var status = response.Status;
                if (status == Status.Success)
                {
                    posResult.ApproveCode = "00";

                    posResult.OrderID = payment.OrderId;
                    posResult.Explanation = "İşlem Başarılı";
                }
                else
                {
                    errorDetail = "3D Doğrulanamadı : ";
                    hatali = true;
                }
            }
            if (aPos.PosGroup == 1)
            {
                #region EST group

                #region Vars

                String nameval = aPos.ApiUserName;              //İşyeri kullanıcı adı
                String passwordval = aPos.ApiPass;      //İşyeri şifresi
                String clientidval = Request.Form.Get("clientid"); // İşyeri numarası
                String modeval = aPos.Mode; // "P";                   //P olursa gerçek işlem, T olursa test işlemi yapar.
                String typeval = "Auth";           //Auth PreAuth PostAuth Credit Void olabilir.
                String expiresval = Request.Form.Get("Ecom_Payment_Card_ExpDate_Month") + "/" + Request.Form.Get("Ecom_Payment_Card_ExpDate_Year"); //Kredi Kartı son kullanım tarihi mm/yy formatından olmalı
                String cv2val = Request.Form.Get("cv2");    //Güvenlik Kodu
                String totalval = payment.TotalAmount.ToString().Replace(",", "."); // Request.Form.Get("amount"); //Tutar
                String numberval = Request.Form.Get("md");    //Kart numarası olarak 3d sonucu dönem md parametresi kullanılır.
                String taksitval = payment.Installment == 1 ? "" : payment.Installment.ToString(); //Taksit sayısı peşin satışlar da boş olarak gönderilmelidir.
                String currencyval = "949";           //ytl için
                String orderidval = payment.OrderId; // "ORID" + payment.UserId.ToString("000000") + Parameters.Now.Year.ToString("0000") + Parameters.Now.Month.ToString("00") + Parameters.Now.Day.ToString("00") + Parameters.Now.Hour.ToString("00") + Parameters.Now.Minute.ToString("00") + Parameters.Now.Second.ToString("00");

                String mdstatus = Request.Form.Get("mdStatus");

                #endregion

                if (mdstatus.Equals("1")) //3D Onayı alınmıştır.
                {
                    #region Create EST Group XML

                    String cardholderpresentcodeval = "13";
                    String payersecuritylevelval = Request.Form.Get("eci");
                    String payertxnidval = Request.Form.Get("xid");
                    String payerauthenticationcodeval = Request.Form.Get("cavv");

                    String ipaddressval = Utils.UserIP;
                    String emailval = eStoreUser.Email;
                    String groupidval = "";
                    String transidval = sesbil;
                    String useridval = payment.UserId.ToString();

                    //Fatura Bilgileri
                    String billnameval = "";      //Fatur İsmi
                    String billstreet1val = "";   //Fatura adres 1
                    String billstreet2val = "";   //Fatura adres 2
                    String billstreet3val = "";   //Fatura adres 3
                    String billcityval = "";      //Fatura şehir
                    String billstateprovval = ""; //Fatura eyalet
                    String billpostalcodeval = ""; //Fatura posta kodu

                    //Teslimat Bilgileri
                    String shipnameval = "";      //isim
                    String shipstreet1val = "";   //adres 1
                    String shipstreet2val = "";   //adres 2
                    String shipstreet3val = "";   //adres 3
                    String shipcityval = "";      //şehir
                    String shipstateprovval = ""; //eyalet
                    String shippostalcodeval = "";//posta kodu

                    String extraval = "";

                    //Ödeme için gerekli xml yapısı oluşturuluyor

                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();

                    System.Xml.XmlDeclaration dec =
                        doc.CreateXmlDeclaration("1.0", "ISO-8859-9", "yes");

                    doc.AppendChild(dec);


                    System.Xml.XmlElement cc5Request = doc.CreateElement("CC5Request");
                    doc.AppendChild(cc5Request);

                    System.Xml.XmlElement name = doc.CreateElement("Name");
                    name.AppendChild(doc.CreateTextNode(nameval));
                    cc5Request.AppendChild(name);

                    System.Xml.XmlElement password = doc.CreateElement("Password");
                    password.AppendChild(doc.CreateTextNode(passwordval));
                    cc5Request.AppendChild(password);

                    System.Xml.XmlElement clientid = doc.CreateElement("ClientId");
                    clientid.AppendChild(doc.CreateTextNode(clientidval));
                    cc5Request.AppendChild(clientid);

                    System.Xml.XmlElement ipaddress = doc.CreateElement("IPAddress");
                    ipaddress.AppendChild(doc.CreateTextNode(ipaddressval));
                    cc5Request.AppendChild(ipaddress);

                    System.Xml.XmlElement email = doc.CreateElement("Email");
                    email.AppendChild(doc.CreateTextNode(emailval));
                    cc5Request.AppendChild(email);

                    System.Xml.XmlElement mode = doc.CreateElement("Mode");
                    mode.AppendChild(doc.CreateTextNode(modeval));
                    cc5Request.AppendChild(mode);

                    System.Xml.XmlElement orderid = doc.CreateElement("OrderId");
                    orderid.AppendChild(doc.CreateTextNode(orderidval));
                    cc5Request.AppendChild(orderid);

                    System.Xml.XmlElement groupid = doc.CreateElement("GroupId");
                    groupid.AppendChild(doc.CreateTextNode(groupidval));
                    cc5Request.AppendChild(groupid);

                    System.Xml.XmlElement transid = doc.CreateElement("TransId");
                    transid.AppendChild(doc.CreateTextNode(transidval));
                    cc5Request.AppendChild(transid);

                    System.Xml.XmlElement userid = doc.CreateElement("UserId");
                    userid.AppendChild(doc.CreateTextNode(useridval));
                    cc5Request.AppendChild(userid);

                    System.Xml.XmlElement type = doc.CreateElement("Type");
                    type.AppendChild(doc.CreateTextNode(typeval));
                    cc5Request.AppendChild(type);

                    System.Xml.XmlElement number = doc.CreateElement("Number");
                    number.AppendChild(doc.CreateTextNode(numberval));
                    cc5Request.AppendChild(number);

                    System.Xml.XmlElement expires = doc.CreateElement("Expires");
                    expires.AppendChild(doc.CreateTextNode(expiresval));
                    cc5Request.AppendChild(expires);

                    System.Xml.XmlElement cvv2val = doc.CreateElement("Cvv2Val");
                    cvv2val.AppendChild(doc.CreateTextNode(cv2val));
                    cc5Request.AppendChild(cvv2val);

                    System.Xml.XmlElement total = doc.CreateElement("Total");
                    total.AppendChild(doc.CreateTextNode(totalval));
                    cc5Request.AppendChild(total);

                    System.Xml.XmlElement currency = doc.CreateElement("Currency");
                    currency.AppendChild(doc.CreateTextNode(currencyval));
                    cc5Request.AppendChild(currency);

                    System.Xml.XmlElement taksit = doc.CreateElement("Taksit");
                    taksit.AppendChild(doc.CreateTextNode(taksitval));
                    cc5Request.AppendChild(taksit);

                    System.Xml.XmlElement payertxnid = doc.CreateElement("PayerTxnId");
                    payertxnid.AppendChild(doc.CreateTextNode(payertxnidval));
                    cc5Request.AppendChild(payertxnid);

                    System.Xml.XmlElement payersecuritylevel = doc.CreateElement("PayerSecurityLevel");
                    payersecuritylevel.AppendChild(doc.CreateTextNode(payersecuritylevelval));
                    cc5Request.AppendChild(payersecuritylevel);

                    System.Xml.XmlElement payerauthenticationcode = doc.CreateElement("PayerAuthenticationCode");
                    payerauthenticationcode.AppendChild(doc.CreateTextNode(payerauthenticationcodeval));
                    cc5Request.AppendChild(payerauthenticationcode);

                    System.Xml.XmlElement cardholderpresentcode = doc.CreateElement("CardholderPresentCode");
                    cardholderpresentcode.AppendChild(doc.CreateTextNode(cardholderpresentcodeval));
                    cc5Request.AppendChild(cardholderpresentcode);

                    System.Xml.XmlElement billto = doc.CreateElement("BillTo");
                    cc5Request.AppendChild(billto);

                    System.Xml.XmlElement billname = doc.CreateElement("Name");
                    billname.AppendChild(doc.CreateTextNode(billnameval));
                    billto.AppendChild(billname);

                    System.Xml.XmlElement billstreet1 = doc.CreateElement("Street1");
                    billstreet1.AppendChild(doc.CreateTextNode(billstreet1val));
                    billto.AppendChild(billstreet1);

                    System.Xml.XmlElement billstreet2 = doc.CreateElement("Street2");
                    billstreet2.AppendChild(doc.CreateTextNode(billstreet2val));
                    billto.AppendChild(billstreet2);

                    System.Xml.XmlElement billstreet3 = doc.CreateElement("Street3");
                    billstreet3.AppendChild(doc.CreateTextNode(billstreet3val));
                    billto.AppendChild(billstreet3);

                    System.Xml.XmlElement billcity = doc.CreateElement("City");
                    billcity.AppendChild(doc.CreateTextNode(billcityval));
                    billto.AppendChild(billcity);

                    System.Xml.XmlElement billstateprov = doc.CreateElement("StateProv");
                    billstateprov.AppendChild(doc.CreateTextNode(billstateprovval));
                    billto.AppendChild(billstateprov);

                    System.Xml.XmlElement billpostalcode = doc.CreateElement("PostalCode");
                    billpostalcode.AppendChild(doc.CreateTextNode(billpostalcodeval));
                    billto.AppendChild(billpostalcode);

                    System.Xml.XmlElement shipto = doc.CreateElement("ShipTo");
                    cc5Request.AppendChild(shipto);

                    System.Xml.XmlElement shipname = doc.CreateElement("Name");
                    shipname.AppendChild(doc.CreateTextNode(shipnameval));
                    shipto.AppendChild(shipname);

                    System.Xml.XmlElement shipstreet1 = doc.CreateElement("Street1");
                    shipstreet1.AppendChild(doc.CreateTextNode(shipstreet1val));
                    shipto.AppendChild(shipstreet1);

                    System.Xml.XmlElement shipstreet2 = doc.CreateElement("Street2");
                    shipstreet2.AppendChild(doc.CreateTextNode(shipstreet2val));
                    shipto.AppendChild(shipstreet2);

                    System.Xml.XmlElement shipstreet3 = doc.CreateElement("Street3");
                    shipstreet3.AppendChild(doc.CreateTextNode(shipstreet3val));
                    shipto.AppendChild(shipstreet3);

                    System.Xml.XmlElement shipcity = doc.CreateElement("City");
                    shipcity.AppendChild(doc.CreateTextNode(shipcityval));
                    shipto.AppendChild(shipcity);

                    System.Xml.XmlElement shipstateprov = doc.CreateElement("StateProv");
                    shipstateprov.AppendChild(doc.CreateTextNode(shipstateprovval));
                    shipto.AppendChild(shipstateprov);

                    System.Xml.XmlElement shippostalcode = doc.CreateElement("PostalCode");
                    shippostalcode.AppendChild(doc.CreateTextNode(shippostalcodeval));
                    shipto.AppendChild(shippostalcode);


                    System.Xml.XmlElement extra = doc.CreateElement("Extra");
                    extra.AppendChild(doc.CreateTextNode(extraval));
                    cc5Request.AppendChild(extra);

                    Logger.Write("Est XML : " + doc.OuterXml.ToString(), "Trace");
                    String xmlval = doc.OuterXml;     //Oluşturulan xml string olarak alınıyor. 

                    #endregion

                    #region Call POS trx

                    // Ödeme için bağlantı kuruluyor. ve post ediliyor
                    String url = aPos.ApiUrl;  //"https://testsanalpos.est.com.tr/servlet/cc5ApiServer";
                    System.Net.HttpWebResponse resp = null;
                    try
                    {
                        System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);

                        string postdata = "DATA=" + xmlval.ToString();
                        byte[] postdatabytes = System.Text.Encoding.GetEncoding("ISO-8859-9").GetBytes(postdata);
                        request.Method = "POST";
                        request.ContentType = "application/x-www-form-urlencoded";
                        request.ContentLength = postdatabytes.Length;
                        System.IO.Stream requeststream = request.GetRequestStream();
                        requeststream.Write(postdatabytes, 0, postdatabytes.Length);
                        requeststream.Close();

                        resp = (System.Net.HttpWebResponse)request.GetResponse();
                        System.IO.StreamReader responsereader = new System.IO.StreamReader(resp.GetResponseStream(), System.Text.Encoding.GetEncoding("ISO-8859-9"));

                        String gelenXml = responsereader.ReadToEnd(); //Gelen xml string olarak alındı.
                        System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
                        xDoc.LoadXml(gelenXml);    //string xml dökumanına çevrildi.


                        #region ApproveCode

                        if (!string.IsNullOrEmpty(aPos.ApproveXMLKey))
                        {
                            try
                            {
                                XmlElement xElement1 = xDoc.SelectSingleNode(aPos.ApproveXMLKey) as XmlElement;
                                if (string.IsNullOrEmpty(aPos.ApproveAttribute))
                                {
                                    posResult.ApproveCode = xElement1.InnerText;
                                }
                                else
                                {
                                    posResult.ApproveCode = xElement1.Attributes[aPos.ApproveAttribute].Value.ToString();
                                }
                            }
                            catch
                            {

                            }
                        }

                        #endregion

                        #region ReasonCode

                        if (!string.IsNullOrEmpty(aPos.ReasonXMLKey))
                        {
                            try
                            {
                                XmlElement xElement1 = xDoc.SelectSingleNode(aPos.ReasonXMLKey) as XmlElement;
                                if (string.IsNullOrEmpty(aPos.ReasonAttribute))
                                {
                                    posResult.ReturnCode = xElement1.InnerText;
                                }
                                else
                                {
                                    posResult.ReturnCode = xElement1.Attributes[aPos.ReasonAttribute].Value.ToString();
                                }
                            }
                            catch
                            {

                            }
                        }

                        #endregion

                        #region ErrorMsg

                        if (!string.IsNullOrEmpty(aPos.ErrMsgXMLKey))
                        {
                            try
                            {
                                XmlElement xElement3 = xDoc.SelectSingleNode(aPos.ErrMsgXMLKey) as XmlElement;
                                if (string.IsNullOrEmpty(aPos.ErrMsgAttribute))
                                {
                                    posResult.Message = xElement3.InnerText;
                                }
                                else
                                {
                                    posResult.Message = xElement3.Attributes[aPos.ErrMsgAttribute].Value.ToString();
                                }
                            }
                            catch
                            {

                            }
                        }
                        else
                        {
                            posResult.Message = posResult.ReturnCode;
                        }

                        #endregion

                        //00 ReasonCode döndüğünde işlem başarılıdır. Müşteriye başarılı veya başarısız şeklinde göstermeniz tavsiye edilir. (Fraud riski)
                        if (posResult.ApproveCode == aPos.ApproveCode)
                        {
                            posResult.OrderID = orderidval;
                            posResult.Explanation = "İşlem Başarılı";
                        }
                        else
                        {
                            posResult.Explanation = "İşlem Başarısız";
                        }





                        //System.Xml.XmlNodeList list = gelen.GetElementsByTagName("Response");
                        //String xmlResponse = list[0].InnerText;
                        //if ("Approved".Equals(xmlResponse))
                        //{

                        //    // ödeme success kodlarını buraya yazın.
                        //}
                        //else
                        //{
                        //    Session["Error_3D"] = "<font color=red>Ödeme işleminde hata</font>";

                        //    return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Checkout/" + "'</script>");
                        //}
                    }
                    catch (Exception ex)
                    {
                        posResult.Message = ex.Message;
                        posResult.ResponseXMLString = "";

                        Logger.Write(ex, "Exception");
                        Session["Error_3D"] = "<span class=\"checkOut-Error-Text\">Beklenmeyen bir hata oluştu!</span>";

                        return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Checkout/" + "'</script>");
                    }
                    finally
                    {
                        if (resp != null)
                            resp.Close();
                    }

                    #endregion
                }
                else
                {
                    #region NOT Full 3D

                    errorDetail = "3D Doğrulanamadı : " + mdstatus;
                    hatali = true;

                    #endregion
                }

                #endregion
            }
            else if (aPos.PosGroup == 3)
            {
                #region VakıfBank Group

                #region Vars

                string status = Request.Form["status"] ?? "";
                string uyeno = Request.Form["uyeno"] ?? "";
                string tutar = Request.Form["tutar"] ?? "";
                string dcins = Request.Form["dcins"] ?? "";
                string xid = Request.Form["xid"] ?? "";

                cavv = Request.Form["cavv"] ?? "";
                eci = Request.Form["eci"] ?? "";

                string sipbil = Request.Form["sipbil"] ?? "";
                string zaman = Request.Form["zaman"] ?? "";
                string ozet = Request.Form["ozet"] ?? "";
                string get724stat = Request.Form["get724stat"] ?? "";

                string xcip = aPos.UserId;
                string uyenoCfg = aPos.StoreNo;

                string hashStr = status + uyeno + tutar + dcins + xid + cavv + eci + sesbil + sipbil + zaman + xcip;

                #endregion

                #region Log

                Logger.Write("status     : " + status, "Trace");
                Logger.Write("uyeno      : " + uyeno, "Trace");
                Logger.Write("tutar      : " + tutar, "Trace");
                Logger.Write("dcins      : " + dcins, "Trace");
                Logger.Write("xid        : " + xid, "Trace");
                Logger.Write("cavv       : " + cavv, "Trace");
                Logger.Write("eci        : " + eci, "Trace");
                Logger.Write("sesbil     : " + sesbil, "Trace");
                Logger.Write("sipbil     : " + sipbil, "Trace");
                Logger.Write("zaman      : " + zaman, "Trace");
                Logger.Write("xcip       : " + xcip, "Trace");
                Logger.Write("ozet       : " + ozet, "Trace");
                Logger.Write("get724stat : " + get724stat, "Trace");

                #endregion

                #region Check Data, Account, Merchant, Hash and 3D

                if (!uyeno.Equals(uyenoCfg))
                {
                    #region Bank UyeNo Control

                    Logger.Write("uyeno hatali", "Trace");
                    errorDetail = "Banka Uye No Uyumsuz";
                    hatali = true;

                    #endregion
                }
                else if (!Security.CheckHash(hashStr, ozet))
                {
                    #region Hash Control

                    Logger.Write("ozet hatalı", "Trace");
                    errorDetail = "İstek detayında uyumsuzluk";
                    hatali = true;

                    #endregion
                }
                else if (status.ToUpperInvariant() != "Y")
                {
                    #region NOT Full 3D

                    errorDetail = "3D Doğrulanamadı : " + status + "-" + get724stat;
                    hatali = true;

                    #endregion
                }

                #endregion

                #endregion
            }

            #region Hatalı !!!

            if (hatali)
            {
                #region Request NOK

                dbPayment.Update(payment.PaymentId, "ERR", errorDetail);

                Session["Error_3D"] = "<span class=\"checkOut-Error-Text\">3D İşleminde Hata Alındı Tekrar Deneyiniz.</span>";

                return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Checkout/" + "'</script>");

                #endregion
            }

            #endregion

            Logger.Write("Everything OK Start Payment Process", "Trace");

            if (aPos.PosGroup == 3)
            {
                #region Request OK

                #region Selected POS or DEFAULT

                if (payment.Installment < 2 && Parameters.DefaultPosId > 0)
                {
                    #region Tek Çekim Default POS kullanımı

                    aPos = PosProcess.GetPos(Parameters.DefaultPosId);
                    if (aPos == null)
                    {
                        Logger.Write("Varsayılan POS bulunamadı 2016 nolu referans = " + Parameters.DefaultPosId.ToString() + ". Seçilen POS ile işleme devam ediliyor", "Exception");
                        aPos = PosProcess.GetPos(id);
                    }

                    #endregion
                }

                Logger.Write("Pos Id : " + aPos.PosId.ToString(), "Trace");

                #endregion
                posResult = oPos.Send(aPos, eStoreUser.Email, payment.Installment.ToString(), payment.UserId, cc, month, year, cvv, cowner, payment.Amount, true, cavv, eci, null);

                #endregion
            }

            bool PaymentSucceeded = false;
            decimal PaymentAmount = 0;
            long PaymentId = 0;
            bool dataOK = true;
            decimal HavaleEFTIndirimi = 1;
            decimal KrediKartIndirimi = 1;
            decimal KomisyonOrani = 1;
            decimal KampanyaKomisyonOrani = 1;
            string OrderPaymentType = "K";

            PaymentAmount = payment.Amount;

            CartCheckOutModel ccoTempModel = Get_ccoModel();

            ccoTempModel.PartialPayment = payment.Amount;
            ccoTempModel.SelectedPos = payment.PosId;
            ccoTempModel.SelectedCargoCompanyId = payment.CargoId;
            ccoTempModel.CargoAddressId = payment.AddressId;
            ccoTempModel.InvoiceAddressId = payment.InvoiceId;
            ccoTempModel.SelectedCargoCompanyId = payment.CargoId;
            ccoTempModel.SelectedInstallment = payment.Installment;

            ccoTempModel.ValidMonth = month;
            ccoTempModel.ValidYear = year;
            ccoTempModel.CVV = cvv;
            ccoTempModel.CardOwnerName = cowner;

            ccoTempModel.CardNumber1 = cc.Substring(0, 4);
            ccoTempModel.CardNumber2 = cc.Substring(4, 4);
            ccoTempModel.CardNumber3 = cc.Substring(8, 4);
            ccoTempModel.CardNumber4 = cc.Substring(12, 4);

            //ccoTempModel.CAVV = cavv;
            //ccoTempModel.ECI = eci;

            CartCheckOutModel ccoModel = Get_ccoModel(ccoTempModel);

            PosInstallment pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();

            if (pi == null)
            {
                ccoModel.SelectedInstallment = 1;
                pi = ccoModel.PosInstallmentList.Where(i => i.InstallmentNumber == ccoModel.SelectedInstallment).ToArray<PosInstallment>().FirstOrDefault();
            }

            ccoModel.ContractTotalPrice = ccoModel.TotalPaymentWithCreditCard;

            string VoucherComment = "";
            string OrderComment = "";

            if (!string.IsNullOrEmpty(ccoModel.PromoCode))
            {
                OrderComment = "PromoCode: (" + ccoModel.PromoCode + ")";
                VoucherComment = "PromoCode: (" + ccoModel.PromoCode + ") ";
            }
            if (!string.IsNullOrEmpty(eStoreUser.UTMReferral))
            {
                OrderComment = OrderComment + " UTM : (" + eStoreUser.UTMReferral + ") ";
                VoucherComment = VoucherComment + " UTM : (" + eStoreUser.UTMReferral + ") ";
            }

            VoucherComment = VoucherComment + posResult.OrderID ?? "";

            #region Log XML

            try
            {
                Logger.Write(aPos.BankName + " -> " + posResult.RequestXMLString.Replace(ccoModel.CardNumber, ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4)), "Trace");
            }
            catch
            { }

            try
            {
                Logger.Write(aPos.BankName + " -> " + posResult.ResponseXMLString.Replace(ccoModel.CardNumber, ccoModel.CardNumber.Substring(0, 4) + " **** **** " + ccoModel.CardNumber.Substring(12, 4)), "Trace");
            }
            catch
            { }

            #endregion

            if (posResult.ApproveCode != aPos.ApproveCode)
            {
                #region Error - Credit Card Checkout

                Logger.Write("Payment NOK", "Trace");

                dbPayment.Update(payment.PaymentId, "ERR", posResult.Explanation + " - " + posResult.Message);

                Session["Error_3D"] = "<span class=\"checkOut-Error-Text\">" + posResult.Explanation + " - " + posResult.Message + "</span>";

                return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Checkout/" + "'</script>");

                #endregion
            }

            #region Success - Credit Card Checkout

            Logger.Write("Payment OK", "Trace");

            dbPayment.Update(payment.PaymentId, "SUC", "");

            PaymentSucceeded = true;

            PaymentId = dbVoucher.Insert(payment.UserId, (short)PaymentTypes.KrediKart.GetHashCode(), true, false, 0, Parameters.Now.AddYears(10), payment.UserId, payment.Amount, true, VoucherComment, false, cowner + " - " + cc.Substring(0, 4) + " **** **** " + cc.Substring(12, 4), aPos.PosId, payment.Installment, aPos.BankId, Parameters.Now);

            KomisyonOrani = pi.CommissionRate;
            KampanyaKomisyonOrani = pi.CampaignCommissionRate;

            if (ccoTempModel.SelectedInstallment > 1)
            {
                KrediKartIndirimi = Parameters.CreditCardDiscount;
            }

            #endregion

            #region PaymentSucceeded

            if (PaymentSucceeded)
            {
                if (Parameters.UsePartialPayment && PaymentAmount < ccoModel.TotalPaymentWithCreditCard)
                {
                    #region Parçalı Ödeme

                    Logger.Write("Partial Payment", "Trace");
                    ViewData.ModelState.Clear();
                    return Content("<script>window.location='" + Parameters.WebSiteSecureUrl + "/Cart/Checkout'</script>");

                    #endregion
                }
                else
                {
                    #region Tüm Ödeme Tamamlandı

                    Logger.Write("Total Payment", "Trace");

                    //string ContractText = CreateContractText(payment.CargoId, payment.InvoiceId, "Kredi Kartı", ccoModel.CargoTotalPrice, ccoModel.ContractTotalPrice, payment.PosId);
                    ccoModel.ContractText = CreateContractText(payment.AddressId, payment.InvoiceId, "Kredi Kartı", ccoModel.CargoTotalPrice, ccoModel.TotalPaymentWithCreditCard, payment.PosId);

                    int orderId = dbCart.CreateOrder(eStoreUser.AccountId, 0, "K", Parameters.Now, ccoTempModel.CargoWithInvoice, eStoreUser.AccountId, KomisyonOrani, KampanyaKomisyonOrani, KrediKartIndirimi, HavaleEFTIndirimi, payment.CargoId, ccoTempModel.CargoPrice, ccoTempModel.CargoPrice2, ccoTempModel.TransportPrice, ccoModel.TransportAvailable, ccoTempModel.InstallationPrice, ccoTempModel.InstallationAvailable, ccoTempModel.CargoAddress.City, OrderComment);

                    #region Selected Vouchers and Payments + Last Payment set as Used

                    foreach (Voucher voucher in ccoTempModel.VoucherList)
                    {
                        if (voucher.Selected)
                        {
                            dbVoucher.Update(eStoreUser.AccountId, voucher.VoucherId, false, true, eStoreUser.AccountId, orderId, false, "");
                        }
                    }

                    dbVoucher.Update(eStoreUser.AccountId, PaymentId, false, true, eStoreUser.AccountId, orderId, false, VoucherComment);

                    #endregion

                    #region Order Addresses Create

                    if (ccoTempModel.CargoAddressId > 0)
                    {
                        dbAddressOrder.Insert(111, orderId, "CAR", string.IsNullOrEmpty(ccoTempModel.CargoAddress.Name) ? ccoTempModel.UserName : ccoTempModel.CargoAddress.Name, "", "",
                                      Convert2.ToString(ccoTempModel.CargoAddress.Address1), Convert2.ToString(ccoTempModel.CargoAddress.Address2),
                                      Convert2.ToString(ccoTempModel.CargoAddress.County), Convert2.ToString(ccoTempModel.CargoAddress.PostalCode),
                                      ccoTempModel.CargoAddress.Country, ccoTempModel.CargoAddress.City, eStoreUser.AccountId, Convert2.ToString(ccoTempModel.CargoAddress.Phone));
                    }

                    if (ccoTempModel.InvoiceAddressId > 0)
                    {
                        dbAddressOrder.Insert(111, orderId, "INV", string.IsNullOrEmpty(ccoTempModel.InvoiceAddress.Name) ? ccoTempModel.UserName : ccoTempModel.InvoiceAddress.Name,
                                              Convert2.ToString(ccoTempModel.InvoiceAddress.TaxOffice), Convert2.ToString(ccoTempModel.InvoiceAddress.TaxNo),
                                              Convert2.ToString(ccoTempModel.InvoiceAddress.Address1), Convert2.ToString(ccoTempModel.InvoiceAddress.Address2),
                                              Convert2.ToString(ccoTempModel.InvoiceAddress.County), Convert2.ToString(ccoTempModel.InvoiceAddress.PostalCode),
                                              ccoTempModel.InvoiceAddress.Country, ccoTempModel.InvoiceAddress.City, eStoreUser.AccountId, Convert2.ToString(ccoTempModel.InvoiceAddress.Phone));
                    }

                    #endregion

                    #region Payment Succeeded Page

                    RefreshCartSummary();

                    string MessageBody = "";

                    MessageBody = dbRefs.GetRef5(122);

                    MessageBody = MessageBody.Replace("{FirstName}", eStoreUser.FirstName).Replace("{LastName}", eStoreUser.LastName);
                    try
                    {
                        Utils.SendMail(eStoreUser.Email, "", Parameters.OrderMailBccAddress, "Siparişiniz Alınmıştır", MessageBody + "<br /><br />" + ccoModel.ContractText, true);
                    }
                    catch (Exception ex)
                    {
                        Logger.Write(ex, "Exception");
                    }

                    return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Order/" + orderId.ToString() + "'</script>");

                    #endregion

                    #endregion
                }
            }

            #endregion

            Logger.Write("BankSuccess Sonu : " + id.ToString(), "Trace");

            return View();
        }

        #endregion

        #region BankFail

        [AllowAnonymous]
        public ActionResult BankFail(int id)
        {
            Logger.Write("BankFail : " + id.ToString(), "Trace");

            NameValueCollection nvColleciton = Request.Form;
            string status = "";
            string sesbil = "";
            string sipbil = "";
            string get724stat = "";

            try
            {
                status = Request.Form["status"];
            }
            catch { }
            try
            {
                sesbil = Request.Form["sesbil"];
            }
            catch
            { }
            try
            {
                sipbil = Request.Form["sipbil"];
            }
            catch
            { }
            try
            {
                get724stat = Request.Form["get724stat"];
            }
            catch
            { }

            Logger.Write((status ?? "-") + "," + (sesbil ?? "-") + "," + (sipbil ?? "-") + "," + (get724stat ?? "-"), "Trace");
            Logger.Write(Request.Form.ToString());
            Logger.Write("BankFail Sonu : " + id.ToString(), "Trace");

            Session["OMAY_Payment_CCNo"] = null;
            Session["OMAY_Payment_Month"] = null;
            Session["OMAY_Payment_Year"] = null;
            Session["OMAY_Payment_CVV"] = null;
            Session["OMAY_Payment_CardOwner"] = null;

            Payment payment = dbPayment.Get(sesbil);
            if (payment != null && payment.Status == "QUE")
            {
                dbPayment.Update(payment.PaymentId, "ERR", "3D İşleminde Hata Alındı - " + get724stat ?? "Hata");
            }

            Session["Error_3D"] = "<span class=\"checkOut-Error-Text\">3D İşleminde Hata Alındı - " + get724stat ?? "Hata" + "</span>";

            return Content("<script>window.location='" + Parameters.WebSiteUrl + "/Cart/Checkout/" + "'</script>");
        }

        #endregion


        #region CalculateCargoPrice

        public static decimal CalculateCargoPrice(short cargoId, short city, PaymentTypes paymentType, int accountId, int accountType)
        {

            CartModel cartModel = new CartModel();
            cartModel.Products = dbCart.GetList(accountId, accountType);
            decimal toplamDesi = 0;
            CartSummaryCargo SummaryCargo = dbCart.GetSummaryCargo(accountId, accountType, cargoId, city, Parameters.CreditCardDiscount, Parameters.TransferDiscount, Parameters.CargoCalculateForSameProduct);
            decimal CargoPrice = 0;
            decimal CargoPrice2 = 0;

            if (SummaryCargo != null)
            {
                if (SummaryCargo.CartItemCount > 0)
                {
                    CargoPrice = Math.Round(SummaryCargo.CartCargoPrice * (Parameters.SetCargoPricesWithoutTax ? 1 : Parameters.CargoList.Where(c => c.CargoId == cargoId).FirstOrDefault().Tax), 2);
                }

                if (SummaryCargo.ListItemCount > 0)
                {
                    CargoPrice2 = Math.Round(SummaryCargo.ListCargoPrice * (Parameters.SetCargoPricesWithoutTax ? 1 : Parameters.ListCargoProductTax), 2);
                }
            }

            #region Cargo Min Limit Control

            if (Parameters.CargoMinLimit > 0 && SummaryCargo.CartTotalPriceCreditCard > Parameters.CargoMinLimit && CargoPrice > Parameters.CargoMinLimitPrice)
            {
                CargoPrice = Parameters.CargoMinLimitPrice;
            }

            #endregion

            #region Cargo Free Limit Control

            if (Parameters.CargoLimit > 0 && SummaryCargo.CartTotalPriceCreditCard > Parameters.CargoLimit)
            {
                CargoPrice = 0;
                CargoPrice2 = 0;
            }

            #endregion

            #region Tek Kargo

            if (Parameters.OnlyOneCargoPrice > 0 && CargoPrice > Parameters.OnlyOneCargoPrice)
            {
                CargoPrice = Parameters.OnlyOneCargoPrice;
            }

            if (paymentType == PaymentTypes.KapidaOdeme)
            {
                CargoPrice = CargoPrice + Parameters.AdditionFeeForPaymentAtDoor;  // Kapıda Ödeme Ek İşlem Ücreti
            }

            #endregion

            #region Ücretsiz Kargo Varsa Tümünü Ücretsiz Yap

            var freeCargoProductAvailable = false;
            foreach (Cart cart in cartModel.Products)
            {
                Product product = dbProduct.Get(cart.ProductId, accountId);
                if (product.FreeCargo)
                {
                    freeCargoProductAvailable = true;
                    break;
                }
            }
            if (CargoPrice > 0 && toplamDesi <= Parameters.FreeCargoDesiLimit && freeCargoProductAvailable)
            {
                CargoPrice = 0;
            }

            #endregion

            return CargoPrice;
        }

        #endregion

        #region Create Account For Payment

        public bool CreateAccountForPayment(CartCheckOutModel ccoModel)
        {
            var VisitorAccountId = eStoreUser.AccountId;
            var GeneratedPassword = Membership.GeneratePassword(8, 0);

            /* Sonra register işlemi yapıp adres ve sepet bilgileri oluşturulan hesaba geçirilecek.*/

            RegisterModel createAccount = new RegisterModel();
            createAccount.FirstName = ccoModel.FirstName;
            createAccount.LastName = ccoModel.LastName;
            createAccount.ConfirmEmail = ccoModel.Email;
            createAccount.Email = ccoModel.Email;
            createAccount.Mobile = ccoModel.Mobile;
            createAccount.Password = GeneratedPassword;
            createAccount.ConfirmPassword = GeneratedPassword;
            createAccount.NewsLetter = false;
            createAccount.CampaingSMSAndEmail = false;
            createAccount.AgreePrivacyPolicy = true;
            createAccount.BirthDay = new DateTime(1900, 1, 1);

            var utmRefferal = "";
            if (!string.IsNullOrEmpty(eStoreUser.UTMReferral))
            {
                if (eStoreUser.UTMReferral == "akakce")
                {
                    utmRefferal = "AA";
                }
                else if (eStoreUser.UTMReferral == "gittigidiyor")
                {
                    utmRefferal = "GG";
                }
                else if (eStoreUser.UTMReferral == "cimri")
                {
                    utmRefferal = "Cİ";
                }
                else if (eStoreUser.UTMReferral == "google")
                {
                    utmRefferal = "GO";
                }
                else
                {
                    utmRefferal = "";
                }
            }

            int RegisteredId = (int)dbAccount.Insert(createAccount.FirstName, createAccount.LastName, createAccount.Email, createAccount.BirthDay, "", "", "", "", 0, "", createAccount.Mobile, "", "", createAccount.Password, createAccount.NewsLetter == true ? 1 : 0, createAccount.CampaingSMSAndEmail == true ? 1 : 0, Parameters.Now, utmRefferal);

            if (RegisteredId > 0)
            {
                dbCart.VisitorToUser(VisitorAccountId, RegisteredId);
                dbAddress.VisitorToUser(VisitorAccountId, RegisteredId);
                if (ccoModel.Guarantor1 == null)
                {
                    ccoModel.Guarantor1 = new Guarantor();
                }
                if (ccoModel.Guarantor2 == null)
                {
                    ccoModel.Guarantor2 = new Guarantor();
                }
                ccoModel.Guarantor1.AccountId = 0;
                ccoModel.Guarantor2.AccountId = 0;
                eStoreUser.SelectedGuarantor1Id = ccoModel.Guarantor1Id > 0 ? dbAccount.InsertGuarantors(RegisteredId, ccoModel.Guarantor1) : 0;
                eStoreUser.SelectedGuarantor2Id = ccoModel.Guarantor2Id > 0 ? dbAccount.InsertGuarantors(RegisteredId, ccoModel.Guarantor2) : 0;
                eStoreUser.AccountId = RegisteredId;
                eStoreUser.AccountType = 0;
                eStoreUser.FirstName = ccoModel.FirstName;
                eStoreUser.LastName = ccoModel.LastName;
                eStoreUser.UserName = ccoModel.FirstName + " " + ccoModel.LastName;
                eStoreUser.Email = ccoModel.Email;
                return true;
            }
            return false;
        }


        #endregion
    }
}
